-2

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?

4

2 回答 2

1

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);

于 2017-12-01T16:39:15.093 回答
0

setinterval() will not return anything until its callback function has been called

That's entirely not true. Set interval returns unique handle immediately, so you can remove interval even before first function run. The callback function, so the first parameter you pass to setInterval is not gonna return anything until it's run. But even after running, its return value is neveer assigned back to the variable hloding unique handle (in your case - var t).

setInterval puts piece of code to the bottom of the stack, so the rest of the code gets executed before it. Effectively, you clear interval before function is executed.

于 2017-12-01T16:40:42.760 回答