setTimeout with Loop in JavaScript

后端 未结 9 1700
挽巷
挽巷 2021-01-05 16:08

I have a very trivial question. For a simple loop with setTimeout, like this:

for (var count = 0; count < 3; count++) {
    setTimeout(function() {
               


        
9条回答
  •  被撕碎了的回忆
    2021-01-05 16:21

    First, setTimeout(function, milliseconds) is a function which takes a function to execute after "milliseconds" milliseconds.

    Remember, JS treats functions as objects, so the for(...) loop will initially produce something like:

    setTimeout( ... ) setTimeout( ... ) setTimeout( ... )

    Now the setTimeout() functions will execute one by one.

    The setTimeout() function will try to find the count variable in the current scope. Failing that, it will go to the outer scope and will find count, whose value is already incremented to 3 by the for loop.

    Now, starting execution....The first alert shows immediately, as the milliseconds is 0, the second alert shows after 1000 ms, and then the third alert shows after 2000 ms. All of them shows Count = 3

提交回复
热议问题