eval 和 setTimeout 循环
我将代码行保存在数组中,并尝试使用 setTimeout() 逐个单元地运行它们。
这可以很好地执行代码:
for (i=0; i<restorePoints.length; i++){
eval(restorePoints[i]);
}
但我希望每次迭代之间有一个短暂的延迟:我想使用 setTimeout() 而不是 eval()。由于某种原因,这些都不起作用:
for (i=0; i<restorePoints.length; i++){
setTimeout(restorePoints[i],1000);
}
或者
for (i=0; i<restorePoints.length; i++){
setTimeout(eval(restorePoints[i]),1000);
}
我该怎么做? 谢谢
I'm holding code lines in an array, and trying to run them cell by cell with setTimeout().
This executes the code well:
for (i=0; i<restorePoints.length; i++){
eval(restorePoints[i]);
}
but I want to have a short delay between every iteration: i want to use setTimeout() instead of eval(). for some reason none of those work:
for (i=0; i<restorePoints.length; i++){
setTimeout(restorePoints[i],1000);
}
or
for (i=0; i<restorePoints.length; i++){
setTimeout(eval(restorePoints[i]),1000);
}
how do I do it?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
循环很快。它将连续创建所有超时,因此所有超时将同时触发。您可以使时间取决于循环变量,即增加每次迭代的时间,或者,我会做的,仅使用一次超时和递归调用:
请注意, eval(string) 和 eval(string) 之间存在差异 和
setTimeout(string, ...)
除了延迟之外:eval
将在当前范围内评估参数,而setTimeout
(和setInterval
) 将在全局范围内对其进行评估。这可能与您相关。
The loop is fast. It will create all timeouts in a row, so all timeouts will fire at the same time. You can either make the time depended on the loop variable, i.e. increasing the time in every iteration, or, what I would do, use only one timeout and a recursive call:
Note that there is a difference between
eval(string)
andsetTimeout(string, ...)
apart from the delay:eval
will evaluate the parameter in the current scope whilesetTimeout
(andsetInterval
) will evaluate it in the global scope.This might be relevant to you.
如果您打算采用其中任何一种方式,则需要将函数调用包装在匿名函数中:
否则,您不会将 eval 设置为在超时时触发,而是设置执行的结果setTimeout 所针对的对象是 Javascript 代码(无论在本例中是什么)。
If you're going to do it either of those ways, you'll need to wrap the function call in an anonymous function:
Otherwise you're not setting the eval to fire in a timeout, you're setting the result of the executing Javascript code (whatever that might be in this case) to be the thing setTimeout is opperating against.