对我来说,setTimeout
函数在 for 循环中不起作用。它在执行所有 for 循环语句后执行。
setTimeout
如果在javascript中使用函数,我将面临这个范围问题。
这是我的代码片段..
... moves[] is an array ..
for(i=0;i<noOfMoves;i++) {
playerName = moves[i].playerName;
timeDiff = moves[i].timeDiff;
console.log("Inside for loop"+ playerName);
setTimeout(function(){
console.log("Inside set time out :"+playerName);
},timeDiff);
....
....
}
但它笨拙地打印出以下输出......
Inside for loopplayer1
Inside for loopplayer2
Inside for loopplayer3
Inside for loopplayer4
.... (noOfMoeves times .. )
Inside set time outplayer1
Inside set time outplayer1
Inside set time outplayer1
Inside set time outplayer1
编辑 :
我想要以下方式的o/p
我期望代码逐行运行..Inside for loop
首先打印“”控制台日志,然后等待“ timeDiff
”期间,然后打印“ Inside settimeout
”功能控制台日志..我该怎么做?——</p>
Inside for loopplayer1
Inside set time outplayer1 // (after waiting for timeDiff time)
Inside for loopplayer2
Inside set time outplayer2 // (after waiting for timeDiff time)
......
......
此外, playerName 变量在每个 settimeout 控制台日志语句中都获得相同的值吗?