Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67469

DOM manipulation inside loop happens too fast

$
0
0

Trying to flash divs in a different color with some time between them (not using jquery). the program works perfectly in the debugger, but when running it all the changes happen too fast and the user can't see a thing.

tried using setTimeout to no avail (probably not using it right)

var TurnNum = 4 //Number of turns
var posArr = [1]
var turnCnt = 1
var currDiv = makeBoard()

document.onkeydown = function (event) {
switch (event.keyCode) {
    case 37:
        //Left Key -1
        posArr[turnCnt] = posArr[turnCnt - 1] - 1
        currDiv = drawMove(currDiv, -1)
        turnCnt++
        break;

    case 39:
        //Right key +1
        posArr[turnCnt] = posArr[turnCnt - 1] + 1
        currDiv = drawMove(currDiv, 1)
        turnCnt++
        break;

    case 40:
        currDiv.classList.remove('selected')
        dimSwitch()
        break;
}
if (turnCnt === TurnNum) {
    currDiv.classList.remove('selected')
    dimSwitch()
}
};
function dimSwitch() {
var turnCnt = 1
var posIndex = 0
var selectedDivs = []
var tempCnt = 0
var tempIndex = 0
var timeNum = getMaxPos()
while (tempCnt < timeNum) {
    var posIndex = posArr.indexOf(turnCnt, tempIndex)
    tempIndex = posIndex + 1
    while (posIndex !== -1) {
        selectedDivs.push(document.getElementById(posIndex + 1 + ''))
        posIndex = posArr.indexOf(turnCnt, tempIndex)
        tempIndex = posIndex + 1

    }

    selectDiv(selectedDivs)
    turnCnt++
    tempCnt++
    for (let index = 0; index < selectedDivs.length; index++) {
        selectedDivs[index].classList.remove('selected')
    }
    selectedDivs = []
}
}

function selectDiv(divs) {
for (let index = 0; index < divs.length; index++) {
    divs[index].classList.add('selected')
}

the function selectDivs should run with some time between each execution whenever using a delay or timeout it freezes or dosent work correctly The user should be able to see which divs are in red ('selected' class) before i remove the class in the for loop.

This is how I tried using setTimeout but the rest of the code keeps running in the background and what i see is all the divs in red:

setTimeout(function(){ 
for (let index = 0; index < selectedDivs.length; index++) { 
       selectedDivs[index].classList.remove('selected') 
   } 
 },1000) 

Viewing all articles
Browse latest Browse all 67469

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>