I am new to javascript and trying to call a function using setTimeout from a for loop. A loop is executed for each nodeList element.
I find that the function I call with setTimeout only executes during the last iteration of the loop. In the example below, I would like to make three separate calls to setTimeout, but I found 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);
}
}
I saw other posts that describe several setTimeout calls. Surprisingly (for me), multiple calls will work if I just pull them out of a 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);
I just can't understand why there is a difference between calling them from a for loop and calling them outside of one.
setInterval . , for .
.