I NEED HELP WITH MY CODE :) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 25

I NEED HELP WITH MY CODE :)

var x = 0; var t; window.onload = function() { var t = setInterval(aFunc, 1000) } function aFunc () { x++; if (x == 10) { clearInterval(t); } } So I have got this code... I have a more complicate code, but this is the part I struggle with... When x reaches 10, the function is still working, the interval is not stopping. Why is that happening?

27th Mar 2017, 8:31 PM
Gami
Gami - avatar
7 Answers
+ 26
Remove var from line 4
27th Mar 2017, 8:32 PM
Jafca
Jafca - avatar
+ 23
Oh yeah.... It works. Thanks... JS is so strange xD
27th Mar 2017, 8:37 PM
Gami
Gami - avatar
+ 19
@Jafca I like your sarcasm 😂😂
28th Mar 2017, 2:10 PM
Gami
Gami - avatar
+ 18
You had a global (I think) variable and then you made a new local variable in the function. So the two t's were different 🍰
27th Mar 2017, 8:38 PM
Jafca
Jafca - avatar
+ 17
@Shiv Mishra I'm glad you told @Gami again. I don't think he got the message the first time 😀
28th Mar 2017, 12:33 PM
Jafca
Jafca - avatar
+ 6
@Jafca yes, "var t" inside the function creates local variable without access from aFunc function
27th Mar 2017, 8:42 PM
Yaroslav Pieskov
Yaroslav Pieskov - avatar
+ 6
put all the things in window.onload
29th Mar 2017, 5:48 AM
Prabhakar Dev
Prabhakar Dev - avatar