For Loop in Javascript outputs value only from last iteration

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

I have this Javascript code, which works as expected:

5条回答
  •  感动是毒
    2020-12-11 08:48

    The var i is incremented to 2 when the setTimeout is executing the function and so it just prints the i value as 2 resulting in test2test2.

    You should use a closure to use the instance of i which will print test1test.

    DEMO: http://jsfiddle.net/mBBJn/1/

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

    Edit: used function args.

提交回复
热议问题