具有在运行时更改的参数的超时函数
我正在尝试以下操作:
var timeout = 300;
var colors = ['aqua', 'limegreen']
for (var i=0; i < 4; ++i) {
console.log(colors[i % colors.length]);
setTimeout(function() { changeColor(colors[i % colors.length]) }, i * timeout);
}
function changeColor(color) {
console.log(color);
}
这不起作用,因为 changeColor 的参数在执行时已解析...这意味着颜色将始终相同。在我的 chrome 中,超时后也无法传递参数:
var color = colors[i % colors.length];
setTimeout(function() { changeColor() }, i * timeout, color);
好吧,我现在有一个可以工作的时间间隔的解决方法......但是因为我在这里学习......这是如何通过暂停?
I'm trying the following:
var timeout = 300;
var colors = ['aqua', 'limegreen']
for (var i=0; i < 4; ++i) {
console.log(colors[i % colors.length]);
setTimeout(function() { changeColor(colors[i % colors.length]) }, i * timeout);
}
function changeColor(color) {
console.log(color);
}
This doesn't work because the parameter for changeColor is resolved when it get's executed...this means, the color will always be the same. In my chrome it also didn't work to pass the params after the timeout:
var color = colors[i % colors.length];
setTimeout(function() { changeColor() }, i * timeout, color);
Well, I now have a workaround with an interval which works...but since I'm here to learn....how is this done with a timeout?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当for循环结束时,调用
changeColor
的匿名函数将被执行。所以它将等于它获得的最后一个值。为了防止捕获闭包中所需的值,请使用匿名函数包装对 setTimeout 的调用:The anonymous function which calls
changeColor
will be executed when for cycle will be ended already. So it will equal to the last value it gets. To prevent this capture the value you need in closure by wrapping the call to setTimeout with anonymous function:你遇到了关闭问题;对
i
值的引用已被捕获,因此所有函数都包含相同的值。您需要执行以下操作来捕获调用时的i
引用:You are suffering from a closure problem; the reference to the value of
i
has been captured and so all the functions contain the same value. You need to do something like this to capture the reference ofi
at the moment of invoking: