I'm currently working on a JavaScript program that aims to change the background color of an element after a delay, similar to how a traffic light functions.
However, I've encountered an issue. When the button is clicked, the function associated with the onclick listener runs. Within this function, there are for loops intended to iterate through each cell and update its color. Each iteration through the loop should ideally change the color of one cell, but instead, all cells are updated once the onclick function completes.
You can view a simplified version of the problem I'm facing here.
let main = document.getElementById('main')
// create 'cells' which are just empty divs (refer to css styles above)
let cells = []
for (let x = 0, numCells = 15; x < numCells; x++) {
let cell = document.createElement("DIV")
cell.setAttribute('class', 'cell')
cells.push(cell)
main.appendChild(cell)
}
// create button to run main logic
const run = document.createElement("BUTTON")
run.innerHTML = 'change colors'
run.addEventListener('click', function() {
console.log('starting program');
// reset all cell colors
for (let cell of cells) {
cell.style.background = 'white'
}
for (let cell of cells) {
// change color of cell
cell.style.background = `hsl(${cells.indexOf(cell) * (360 / cells.length)}, 100%, 50%)`
// halt program for 500ms
sleep(100)
}
console.log('done');
})
main.appendChild(run)
// sleep function halts entire program during period of ms
function sleep(milliseconds) {
console.log(`waiting ${milliseconds} milliseconds`);
const start = Date.now();
let current = null;
do {
current = Date.now();
} while (current - start < milliseconds);
}
.main {
display: flex;
}
.cell {
width: 20px;
height: 20px;
border: 1px solid black;
margin: 1px;
}
<div id="main" class="main"></div>
The same issue arises when introducing new elements, modifying innerHTML, or any other DOM changes.
I also believe that the 'sleep' function isn't causing the problem, as it simply pauses the entire program in the browser until a specified number of milliseconds have passed (it continuously calls Date.now() until the time delta surpasses the specified duration).
If anyone has any suggestions or solutions, I would greatly appreciate it. Thank you!