For a loop with setTimeout prints the number to the console

enter image description here I read about closure and find this code.

for(i=0;i<5;i++){
    setTimeout(function(){
        console.log(i);
    },2000)
}

      

This outputs 5 times 5 times after 2 seconds. I understand this, but before five appears, there is a number above it. And when I execute this code again, it changes it to 5. What is this? Write the code in the console, see what it outputs and explain to me what it is?

+3


source to share


2 answers


This is the "result" value of the evaluated statement, which for the loop is the result value of the last statement in the body of the loop, which is the return value of the call setTimeout

. And which returns the id of the timer (which allows you to cancel the timeout).

You can also see this behavior with simpler statements:



> 0;
< 0
> console.log(1);
  1  // the output of the log()
< undefined
> var i=2;
< undefined // a declaration has no result
> var i=3; i;
< 3
> for (;i<3;i++) 4;
< undefined // the body was not evaluated
> for (;i<4;i++) 5;
< 5

      

Notice how the leading arrow represents input and outcome.

+4


source


That number is the intervalID

      

Code: when you run the below code in browser debugger

setTimeout(() => console.log('hello'), 2000);

      

The answer will be similar to



> 1822
> hello

      

You can use this ID interval to remove the timeout

Just to show you the confirmation of this number as intervalID

> var test = setTimeout(() => console.log('hello'), 2000); test;
< 11272
  hello
> console.log(test);
  11272
< undefined

      

0


source







All Articles