Javascript setTimeout 与 for 循环中的函数
使用 Javascript,我尝试循环遍历数组并在每个循环上执行一个带有时间延迟的函数。这不起作用:
<script type="text/javascript">
movesArray = new Array("s","s","s","s","s","s","s","s","s","s","s","s","s","s");
var pause = 100;
for (i=0; i<=14; i++)
{
var t=setTimeout("ProcessKeypress(movesArray[i])", pause);
pause = pause+100;
}
</script>
但是,如果我只是重复多次,它确实有效:
<script type="text/javascript">
var t=setTimeout("ProcessKeypress('s')", 100);
var t=setTimeout("ProcessKeypress('s')", 200);
var t=setTimeout("ProcessKeypress('s')", 300);
var t=setTimeout("ProcessKeypress('s')", 400);
var t=setTimeout("ProcessKeypress('s')", 500);
</script>
问题是,在某些情况下,我需要重复该功能几百次(可能更多),从而创建一个大网页。有没有办法循环遍历数组并延迟运行该函数?
Using Javascript, I'm trying to loop through an array and execute a function with a time delay on each loop. This does not work:
<script type="text/javascript">
movesArray = new Array("s","s","s","s","s","s","s","s","s","s","s","s","s","s");
var pause = 100;
for (i=0; i<=14; i++)
{
var t=setTimeout("ProcessKeypress(movesArray[i])", pause);
pause = pause+100;
}
</script>
However, if I just repeat it multiple times it does work:
<script type="text/javascript">
var t=setTimeout("ProcessKeypress('s')", 100);
var t=setTimeout("ProcessKeypress('s')", 200);
var t=setTimeout("ProcessKeypress('s')", 300);
var t=setTimeout("ProcessKeypress('s')", 400);
var t=setTimeout("ProcessKeypress('s')", 500);
</script>
The problem is that in some cases I will need to repeat the function a few hundred times (maybe more) which creates a large webpage. Is there a way to loop through the array and run the function on a time delay?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在传递字符串“movesArray[i]”。只需转义字符串即可
You are passing the string "movesArray[i]". Just escape the string
使用setInterval()。您可以以任意时间间隔运行函数:
此外,请在 setTiemout 中使用
function(){}
而不仅仅是代码:Use
setInterval()
. You can run a function at any interval:Also, use
function(){}
inside the setTiemout instead of just the code:如果您希望循环的每次迭代在前一次迭代完成后都有一定的时间延迟,那么您的执行方式将会在数组索引方面出现问题。这些是我看到的问题:
ProcessKeypress()
的所有调用都会有 i == 15。setTimeout()
实际的 javascript 函数而不是它必须计算的字符串。movesArray[14]
,但数组中没有那么多项目。最好引用数组.length
而不是硬编码14
。我的建议可以这样实施:
If you want each iteration of the loop to go a certain time delay after the previous one finishes, then your way of doing it will have an issues with the index into the array. These are the issues I see:
ProcessKeypress()
will have i == 15.setTimeout()
an actual javascript function rather than a string that it has to evaluate.movesArray[14]
, but you didn't have that many items in the array. It's better to refer to the array.length
rather than hard code the14
.My suggestions can be implemented like this: