Passing parameters into a closure for setTimeout

前端 未结 3 1515
野趣味
野趣味 2021-01-19 02:18

I\'ve run into an issue where my app lives in an iframe and it\'s being called from an external domain. IE9 won\'t fire the load event when the iframe loads properly so I t

3条回答
  •  庸人自扰
    2021-01-19 02:50

    This is a usual problem when you work with setTimeout or setInterval callbacks. You should pass the i value to the function:

    var timings = [1, 250, 500, 750, 1000, 1500, 2000, 3000],
        func = function(i) {
            return function() {
                console.log(timings[i]);
            };
        };
    
    for (var i = 0, len = timings.length; i < len; i++) {
        setTimeout(func(i), timings[i]);
    }
    

    DEMO: http://jsfiddle.net/r56wu8es/

提交回复
热议问题