【问题标题】:loss of parameters when using windows.setTimeout使用 windows.setTimeout 时参数丢失
【发布时间】:2013-02-11 12:00:00
【问题描述】:

我想用 JavaScript 显示一个正在进行的数字。

为此,我开发了以下示例:

for(var i=0; i<100; i++) {
  window.setTimeout(function() {
    alert(i);
  },1000*i);
}

不幸的是,数字 100 每次都显示。我想是因为i 是一个参考?

这在参数传递中怎么改?

【问题讨论】:

标签: javascript parameters reference parameter-passing settimeout


【解决方案1】:

问题在于 JS 不会等待,而是在超时到期之前继续完成循环。到那时,i 已经是 100 了。

要解决此问题,您的超时应具有i 的本地引用。这样,它不会引用到那时已经 100 的 i,而是在循环的那个时候引用 i

for(var i=0; i<100; i++) {
  (function(i){
    //shadowing the loop-i with the function-i
    window.setTimeout(function() {
      //thus, this callback is referencing the i from the function
      //and not the loop's i
      alert(i);
    },1000*i);
  }(i));
}

【讨论】:

    猜你喜欢
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2017-02-23
    • 2016-10-22
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多