Browser console output has a mysterious number in for loop with settimeout?

后端 未结 2 441
眼角桃花
眼角桃花 2021-01-16 21:37

Running this on console displays some details right after, followed by the actual console logs. What does those details mean in different browser?

相关标签:

2条回答
  • 2021-01-16 22:04

    You're scheduling 10 console.log statements at the end of the call stack (when the function returns after the for loop has completed). Since i is 10 at this point, it prints 10 as many times as you've called setTimeout with that handler.

    EDIT

    Upon clarification of the question, what you are seeing is the value of the last expression evaluated. In this case it is the value of the last timeout you had set. window.setTimeout returns an ID that is cancellable and unique for the tab session. In this case, it seems like the browsers are incrementing a count they already had stored, so you're getting increments of 10 because you're calling setTimeout 10 times in the loop.

    0 讨论(0)
  • 2021-01-16 22:10

    Your setTimeout() calls create functions that all reference the exact same variable, that i defined in the for loop. When the loop is finished, the value of i will be 10, so that's what's logged when the timer handlers fire.

    0 讨论(0)
提交回复
热议问题