0

When you run this code

Promise.resolve(console.log('resolved'))
  .then(pass => setTimeout((pass) => console.log(`1 then pass=${pass}`), 1000, pass))
  .then(pass => setTimeout((pass) => console.log(`2 then pass=${pass}`), 1000, pass))
  .then(pass => setTimeout((pass) => console.log(`3 then pass=${pass}`), 1000, pass))
  .then(pass => setTimeout((pass) => console.log(`4 then pass=${pass}`), 1000, pass))
  .then(pass => console.log(`5 then pass=${pass}`))
  .then(pass => console.log(`6 then pass=${pass}`))

you get this in console

resolved
5 then pass=4
6 then pass=undefined
1 then pass=undefined
2 then pass=1
3 then pass=2
4 then pass=3

So the question is where this pass variable gets it's value? Where it is stored as window.pass == undefined? Why it increment? Why it finaly gets undefined as we stop using setTimeout?

What Ever
  • 27
  • 4
  • 1
    `setTimeout` returns a number (identifier). `.then` returns a new Promise resolving to the value returned by the callback you pass to it. Here, your callbacks `return setTimeout()`, so they return that number, which happens to increment every time you create a new timeout – blex Jun 14 '20 at 20:03
  • Thnx. Why it increment though? Like this TimerID stays forever on? – What Ever Jun 14 '20 at 20:19
  • It increments because it has to be unique. Just like when using an Integer Primary key in a database, it's common to make it increment so that it stays unique. It does not stay "forever" though, once you close/reload the page, it can start from the beginning again (back to 1) – blex Jun 14 '20 at 20:29

1 Answers1

3

setTimeout returns a TimerID, so that's the value being passed around.

1 and 6 are the results of console.log calls which return undefined.

MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • Thnx. Why it increment though? Like this TimerID stays forever on? – What Ever Jun 14 '20 at 20:17
  • 1
    Well I don't know if there are spec rules for the integer but each call should produce an identifier for each timer. The whole purpose of it is to be able to cancel the timers/intervals with `clearTimeout`/`clearInterval` basically. – MinusFour Jun 14 '20 at 20:24