我正在尝试设置五个交错的函数调用(相隔一秒发生)。那部分工作正常。什么行不通,我不能将值0到4传递给回调函数。它每次只传递'5'。我似乎无法弄清楚为什么以及如何解决它。
I'm trying to set five staggered function calls (happening one second apart). That part works fine. What doesn't work is, I can't pass values 0 through 4 into the callback function. It just passes '5' each time. I can't seem to figure out why and how to fix it.
代码:
function callback(num) { console.log(num); } for (var i = 0, loadDelay = 1000; i < 5; ++ i, loadDelay += 1000) setTimeout(function() { callback(i); }, loadDelay);结果:
5 5 5 5 5所需结果:
0 1 2 3 4推荐答案
那是因为你创建了一个闭包。因此,传递给 setTimeout 的函数共享相同的 i 实例。在支持标准(不是IE)的浏览器中,您可以:
That's because you create a closure. So the function you pass to setTimeout share the same i instances. In the browser that supports the standards (not IE) you could have:
setTimeout(callback, loadDelay, i);参见: www.whatwg/specs/web-apps/current-work/multipage/timers.html#计时器
否则你必须实际 bind 该函数的参数:
Otherwise you have to actually bind the argument to the function:
setTimeout(callback.bind(undefined, i), loadDelay);请参阅: developer.mozilla/en/JavaScript/Reference/Global_Objects/Function/bind
如果浏览器不支持ES5 bind 方法,您可以实现上面链接中的垫片,也可以手动执行以下操作:
If the browser doesn't support ES5 bind method, you can either implement the shim present in the link above, or manually doing something like:
setTimeout(function(index){ return function() { callback(index) } }(i), loadDelay);但我会说使用 bind 并且值得实施垫片。您实际上可以使用它: github/kriskowal/es5-shim
But I would say it's more readable using bind and it's worthy to implement the shim. You can actually use this: github/kriskowal/es5-shim
在本地不支持es5的浏览器中添加es5功能(尽可能)。
To add es5 capabilities (where is possible) in the browser that don't support es5 natively.
更多推荐
如何将变量传递给setTimeout函数?
发布评论