4

enter image description hereI read about closures and find this code.

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

This outputs 5 number 5 times after 2 second. I understand this but before five appears there is number above him. And when I execute again this code it changes it adds 5 to his old value. What is it? Write code on console, see what it outputs then explain me what is it?

2 Answers2

4

It's the "result" value of the evaluated statement, which for a loop is the result value of the last statement in the loop body, which is the return value of the setTimeout call. And that returns a timer id (which allows you to cancel the timeout).

You also can see this behaviour with more simple 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 result output.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I never paid attention to those tiny tiny *>* *<* good explanation :) – exexzian Apr 01 '17 at 16:35
  • I find it curious that `var a = 3;` outputs `undefined`, `var b = 3; b;` outputs `3`, but `var c = 3; c; var d = 3;` outputs `3` not `undefined`. So the eventual output isn't simply the result of the last statement in a multi-statement line. – Andrew Willems Mar 25 '18 at 00:15
1
That number is the intervalID

Code: when you run the below code in browser debugger

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

Response would be like

> 1822
> hello

You can use that intervalID to remove clear the timeout

Just to show you the confirmation of that number as intervalID

> var test = setTimeout(() => console.log('hello'), 2000); test;
< 11272
  hello
> console.log(test);
  11272
< undefined
Mohan Ram
  • 8,345
  • 25
  • 81
  • 130