[英]do while loop with setTimeout causing infinite loop
我正在开发simon游戏(一种遵循颜色模式的游戏)。 它通过计算机第一轮和我的第一轮,但是尝试在每个计算机选择之间执行setTimeout会导致使用do while语句导致无限循环,或者如果我使用for循环,则同时播放两个选择。 highlightDiv函数仅在div上执行toggleClass,然后执行setTimeout将类切换回关闭状态。 audioStart函数使用switch语句确定要播放的声音,然后使用setTimeout半秒钟播放该声音。 我认为此setTimeout在增量上将允许足够的时间使这两种情况发生,然后再递增,然后在computerChoice数组中进行下一个索引。 如果这样更容易,可以使用codepen: http ://codepen.io/RawleJuglal/pen/pgRVKd
var computerChoice = ["red", "yellow"],index=0;
function computerPattern(cPattern, index){
console.log("Entered computer pattern function");
console.log("This is cPattern");
console.log(cPattern);
console.log("This is index: "+ index);
if(index !== cPattern.length)
{
highlightDiv(cPattern[index]);
audioStart(cPattern[index]);
index++;
computerPattern(cPattern, index);
}
else
{
index=0;
}
console.log("Leaving computerPattern function");
}
computerPattern(computerChoice, index);
永远不会调用您的超时函数,因为您没有机会。 只要您的代码正在运行(循环),浏览器就无法运行使用同一线程的计划脚本。 您将不得不重新考虑代码。
Javascript是单线程的,超时的概念意味着您将一个函数放在一个特殊的队列中,该队列将在到期时执行回调。 现在,由于在您的代码中,仅在3秒钟后才在超时函数中更新i变量,这意味着循环主体将一次又一次地运行,直到满足3秒钟为止。
在3秒钟内,javascript可以运行数千次迭代,并且每次迭代都会注册另一个超时,这意味着事件队列被cPattern.length
,并且单线程将很难完成所有这些任务,直到我最终达到cPattern.length
为止。
您的解决方案可能使用了setInterval
,该setInterval
的回调函数可以执行您想要的操作,并在每次迭代变量停止时都递增,就像这样:
var interval = setInterval(function(){
console.log(cPattern[i]);
highlightDiv(cPattern[i]);
audioStart(cPattern[i]);
i++;
if(i >= cPattern.length){
clearInterval(interval);
}
},
2000);
您要在传递给setTimeout的匿名函数委托中递增一个名为i
的变量。 do-while循环所依赖的局部作用域变量i
永远不会更新。
根据所需的功能,可以在变量i
仍在作用域内时对其进行递增,然后使用闭包将其值的快照传递给setTimeout函数委托。
function run(){
var i = 0
do{
(function(i){
setTimeout(function(){
alert(i);
},1000);
})(i++)
}
while(i < 2);
}
run();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.