For Loop in Javascript outputs value only from last iteration

前端 未结 5 1805
一向
一向 2020-12-11 07:44

I have this Javascript code, which works as expected:

5条回答
  •  不知归路
    2020-12-11 08:33

    The for loop doesn't create a new scope, you can use another function to do it:

    var timeInterval = 1000;
    for (var i = 0, l = 2; i < l; i++) {
        setTimeout((function(i) {
            return function() {
                $(".test").append("test" + i);
            }
        })(i), timeInterval);
        timeInterval += 1000;
    }
    

提交回复
热议问题