在循环中调用 setTimeout 函数 [英] Calling setTimeout function within a loop

查看:50
本文介绍了在循环中调用 setTimeout 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 javascript 新手,正在尝试使用 setTimeout 从 for 循环中调用一个函数.循环为 nodeList 的每个成员执行.

I'm new to javascript and am trying to call a function using setTimeout from within a for loop. The loop executes for each member of a nodeList.

我发现我用 setTimeout 调用的函数实际上只在循环的最后一次迭代期间执行.在下面的示例中,我想对 setTimeout 进行三个单独的调用,但我发现前两个调用被忽略了.

I'm finding that the function I'm calling with setTimeout is only actually executing during the last iteration of the loop. In the example below, I would like to make three separate calls to setTimeout but I'm finding that the first two calls are ignored.

function moveants(e, stepdistance) {

    . . . . .

    for(var i = 0; i < 3; i++)
    {
        var nextAnt = antgroup.childNodes[i]
        nextAnt.count = 0;
        nextAnt.member = i;
        setTimeout(function () { takeStep(nextAnt, mouseclickX, mouseclickY, 10) }, 0);
    }
}

function takeStep(ant, destX, destY, stepDistance) {

    . . . .

    . . . .

    if( condition )
    {
        return;
    }
    else
    {
        takeStep(ant, destX, destY, stepDistance);
    }
}

我看过其他帖子,描述了制作多个调用 setTimeout.令人惊讶的是(对我而言),如果我像这样简单地将它们从 for 循环中取出,那么多个调用将起作用.

I have seen other posts that describe making multiple calls to setTimeout. Amazingly (to me), the multiple calls will work if I simply take them out of the for loop like this.

    setTimeout(function () { takeStep(antgroup.childNodes[0], 
         mouseclickX, mouseclickY, 10) }, 10);
    setTimeout(function () { takeStep(antgroup.childNodes[1], 
         mouseclickX, mouseclickY, 10) }, 10);
    setTimeout(function () { takeStep(antgroup.childNodes[2], 
         mouseclickX, mouseclickY, 10) }, 10);

我只是不明白为什么在 for 循环内调用它们和在循环之外调用它们之间存在差异.

I just can't figure out why there is a difference between calling them from within a for loop and calling them outside of one.

在每种情况下,我都从 setInterval 调用中获得有效的返回值.. 只是只有 for 循环的最后一次迭代才真正执行该函数.

I am getting valid return values from the setInterval call in every case.. it's just that with only the last iteration of the for loop does the function actually execute.

在此先感谢您的帮助.

推荐答案

nextAnt 将在每个循环中被覆盖,因此 takeStep() 将被调用 3 次,但始终使用相同的参数.

nextAnt will be overwritten on every loop, so takeStep() will be called 3 times, but always with the same arguments.

你可以试试这个:

(function(a,b,c){
     setTimeout(function(){
                           takeStep(a,b,c,10)}, 0);
      })(nextAnt, mouseclickX, mouseclickY);

这篇关于在循环中调用 setTimeout 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆