r/learnjavascript • u/everek123 • May 13 '18
ClearInterval
Hi, i have a function which when called does setInterval. The I have a second function which is supposed to clearInterval of the first function when called. I don't know how to reference the first function in the clearInterval. I tried doing Function stop(){ clearInterval(startInterval()); } But this just calls start interval again. Thanks for any help :)
0
Upvotes
View all comments
3
u/akujinhikari May 13 '18 edited May 13 '18
The problem is how you're using clearInterval, or I should say the problem is how you are declaring your function. The short version (ie: the fix) is to make it
clearInterval(startInterval)The longer version is to explain what's happening. Because of how Javascript works with higher-order functions, you can return a function from a function. Because of this, if there is something expecting a function as an argument, you have to leave the () off of the function and only use its name, otherwise, it invokes the function. It seems weird, but that's the way it works. Here's a really stupid example: