Passing parameters into a closure for setTimeout

前端 未结 3 1483
野趣味
野趣味 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:33

    This is happening because you are not closing around the value of i in your func. When the loop is done, i is 8 (timings.length), which doesn't exist in the array.

    You need to do something like this:

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

提交回复
热议问题