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

后端 未结 2 443
眼角桃花
眼角桃花 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.

提交回复
热议问题