Javascript 循环内的DOM操作发生得太快

Javascript 循环内的DOM操作发生得太快,javascript,html,settimeout,delay,Javascript,Html,Settimeout,Delay,尝试以不同颜色闪烁div,间隔一段时间(不使用jquery)。该程序在调试器中工作得很好,但在运行它时,所有更改发生得太快,用户看不到任何东西 尝试使用setTimeout无效(可能没有正确使用) 函数makeBoard(){ var squareNum=4 选择的变量 容器=document.createElement('div') container.id='container' 文件.正文.附件(容器); for(让索引=0;索引

尝试以不同颜色闪烁div,间隔一段时间(不使用jquery)。该程序在调试器中工作得很好,但在运行它时,所有更改发生得太快,用户看不到任何东西

尝试使用setTimeout无效(可能没有正确使用)

函数makeBoard(){
var squareNum=4
选择的变量
容器=document.createElement('div')
container.id='container'
文件.正文.附件(容器);
for(让索引=0;索引maxNum)maxNum=posArr[index]
}
返回最大值
}
var TurnNum=4//圈数
var posArr=[1]
var turnCnt=1
var currDiv=makeBoard()
document.onkeydown=函数(事件){
开关(event.keyCode){
案例37:
//左键-1
posArr[turnCnt]=posArr[turnCnt-1]-1
currDiv=drawMove(currDiv,-1)
转变++
打破
案例39:
//右键+1
posArr[turnCnt]=posArr[turnCnt-1]+1
currDiv=drawMove(currDiv,1)
转变++
打破
案例40:
currDiv.classList.remove('selected')
dimSwitch()
打破
}
如果(turnCnt==TurnNum){
currDiv.classList.remove('selected')
dimSwitch()
}
};
函数selectDivs应该在每次执行之间运行一段时间 无论何时使用延迟或超时,它都会冻结或正常工作 在我删除for循环中的类之前,用户应该能够看到哪些div是红色的(“selected”类)

这是我尝试使用setTimeout的方式,但其余代码仍在后台运行,我看到的是红色的所有div:

setTimeout(function(){ 
for (let index = 0; index < selectedDivs.length; index++) { 
       selectedDivs[index].classList.remove('selected') 
   } 
 },1000) 
setTimeout(函数(){
对于(让index=0;index
您已将循环代码放入setTimeout块中,因此整个循环将在1000毫秒后一眼就能运行。如果您希望元素一个接一个地出现1秒延迟,可以将逻辑更改为此,以便为每个元素设置不同的超时
(1000*索引)

for (let index = 0; index < selectedDivs.length; index++) { 
   setTimeout(function(){ 
        selectedDivs[index].classList.remove('selected') 
    }
    , (1000 * index)
    )
} 
for(让index=0;index
您已将循环代码放入setTimeout块中,因此整个循环将在1000毫秒后一眼就能运行。如果您希望元素一个接一个地出现1秒延迟,可以将逻辑更改为此,以便为每个元素设置不同的超时
(1000*索引)

for (let index = 0; index < selectedDivs.length; index++) { 
   setTimeout(function(){ 
        selectedDivs[index].classList.remove('selected') 
    }
    , (1000 * index)
    )
} 
for(让index=0;index
简单的方法是执行递归循环,使用超时来延迟对自身的调用。概念证明如下:

var childDivs=document.queryselectoral('.child'); 功能选择divs(divs、index、delay){ divs[index].classList.add('selected'); 延迟=延迟| | 1000;//如果要更改延迟 索引++ if(索引<分段长度){ setTimeout(函数(){ 选择divs(divs、index、delay); },延误); } }
.flex容器{
显示器:flex;
柔性包装:包装;
}
.孩子{
高度:100px;
宽度:100px;
框大小:边框框;
背景颜色:黄色;
边框:1px实心#000;
}
.选定{
背景色:红色;
}

简单的方法是执行递归循环,使用超时来延迟对自身的调用。概念证明如下:

var childDivs=document.queryselectoral('.child'); 功能选择divs(divs、index、delay){ divs[index].classList.add('selected'); 延迟=延迟| | 1000;//如果要更改延迟 索引++ if(索引<分段长度){ setTimeout(函数(){ 选择divs(divs、index、delay); },延误); } }
.flex容器{
显示器:flex;
柔性包装:包装;
}
.孩子{
高度:100px;
宽度:100px;
框大小:边框框;
背景颜色:黄色;
边框:1px实心#000;
}
.选定{
背景色:红色;
}


显然,此代码将立即运行。您是如何使用setTimeout的,但没有工作的?setTimeout(函数(){for(让index=0;index