带有for循环函数的Javascript setTimeout

时间:2011-12-09 00:26:17

标签: javascript settimeout

使用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>

问题在于,在某些情况下,我需要重复几百次(可能更多)功能,这会创建一个大型网页。有没有办法循环遍历数组并在延时时间内运行函数?

3 个答案:

答案 0 :(得分:2)

您正在传递字符串“movesArray [i]”。只是逃避字符串

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;
}

答案 1 :(得分:1)

使用setInterval()。您可以在任何时间间隔运行函数:

setInterval(function(){
    // do stuff
}, 300);

另外,在setTiemout中使用function(){}而不是代码:

setTimeout(function(){
    // do stuff
}, pause);

答案 2 :(得分:1)

如果您希望循环的每次迭代在前一次迭代完成后都会延迟一段时间,那么您执行此操作的方式将导致数组中的索引出现问题。这些是我看到的问题:

  1. 您的索引不正确,因为对ProcessKeypress()的所有来电都有i == 15。
  2. 最好传递setTimeout()一个实际的javascript函数,而不是它必须评估的字符串。
  3. 并且,我认为通常在第一次完成时设置下一个计时器而不是一次设置所有计时器更好(尽管两者都可以工作)。
  4. 并且,您的代码最多可达movesArray[14],但您在数组中没有那么多项。最好引用数组.length而不是硬编码14
  5. 我的建议可以像这样实施:

    <script type="text/javascript">
    movesArray = new Array("s","s","s","s","s","s","s","s","s","s","s","s","s","s");
    var i = 0;
    
    function nextIteration() {
        ProcessKeypress(movesArray[i++]);
        if (i < movesArray.length) {
            setTimeout(nextIteration, 100);
        }
    }
    
    nextIteration();
    
    </script>