We all know that when a function on completion can return a value. Now consider the following line of code
var t = setInterval(function() {
console.log('hey hi hello now 2 seconds have passed down');
} ,2000);
clearInterval(t);
Now, clearInterval()
takes the unique id returned by the setInterval()
function as an argument and this will only be returned once the function has completely run. What happens in my code, is that before my setInterval()
function runs, it gets cleared and this should not be possible as setinterval()
will not return anything until its callback function has been called.
How is the clearInterval()
function able to run before the setinterval()
function?
What happens is you call setInterval
function at the first time in the first line of your code, it returns an ID for it.
This ID not related to the invoke of the function, After that you tell the JS to remove this interval. so no thing will happen.
These are the steps that happens:
// Step #1
var t = setInterval(
// Step #3
function () {console.log('hey hi hello now 2 seconds have passed down');}
, 2000);
clearInterval(t);// Step #2
So the problem is that you clear the interval before the invoking of the function. but after the declaration.
Wrong!
1- Declare -> Clear -> Invoke
Correct
1- Declare -> Invoke -> Clear
As as solution:
call clearInterval
inside setInterval
.
Like this:
var t = setInterval(function () {
console.log('hey hi hello now 2 seconds have passed down');
clearInterval(t);
}, 2000);