For Loop in Javascript outputs value only from last iteration

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

I have this Javascript code, which works as expected:

5条回答
  •  不思量自难忘°
    2020-12-11 08:27

    This is because you aren't capturing the value of i from the for-loop. You can tweak your code to this to make it work:

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

提交回复
热议问题