setTimeout with Loop in JavaScript

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

    This is to do with closure scoping. The same variable count is available in the scope for each of the setTimeout callback functions. You are incrementing its value and creating a function, but each instance of the function has the same variable count in its scope, and by the time the callback functions execute it will have the value 3.

    You need to create a copy of the variable (e.g. var localCount = count) inside a new scope in the for loop to make this work. As for doesn't create a scope (which is the cause of the whole thing) you need to introduce one with a function scope.

    e.g.

    for (var i = 0; i < 5; i++) {
      (function() {
        var j = i;
        setTimeout(function() {
          console.log(j)
        },
        j*100);
       })();
     }
    

提交回复
热议问题