setTimeout with Loop in JavaScript

后端 未结 9 1585
挽巷
挽巷 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:12

    That is because by the time the for loop completes its execution the count is 3, and then the set timeout is called.

    Try this:

    var count = 0; 
    setTimeout(function() {
           for (count = 0; count < 3; count++) {
               alert("Count = " + count);
            }
    }, 1000* count);
    

提交回复
热议问题