-3

Running the following code in the console:

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

results in some strange behavior. When I run it once, I see something like:

enter image description here

What is that number at the top?

9 // what is this????
0
1
2
3
4

The next time I run it, it's different:

13 // what is this????
0
1
2
3
4
4
  • That's the return value of setTimeout(). In browsers, the handle is a positive integer that can be passed to clearTimeout() before the callback is scheduled to execute if you want to cancel it. Commented Feb 18, 2020 at 7:50
  • Its return value of setTimeout function to be stored and used in case clearTimeout is needed. Commented Feb 18, 2020 at 7:53
  • Thanks, I first thought it's returning some stack size. Commented Feb 18, 2020 at 7:58
  • Relevant part from the spec (wrt duplicate): ecma-international.org/ecma-262/10.0/… Commented Feb 18, 2020 at 8:20

1 Answer 1

1

The console will log the result of the final expression that was evaluated. This is why, for example, typing in

'foo' + 'bar'

results in 'foobar' being logged.

Here, the final expression evaluated (synchronously) is the setTimeout, and setTimeout returns an integer indicating the ID of the timeout (which can be used with clearTimeout later). setInterval works the same way. So the number you're seeing is that timeout ID. (it sounds like setTimeout was called 12 times previously on that load of the page)

Sign up to request clarification or add additional context in comments.

1 Comment

It's not "just" the final expression (if that was the case, var foo = 1 would log 1), it's the "result" of the for loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.