Let’s say I have an array of 10000 random integers. I want to while loop through it and add each number to a ul
. The thing is, if I do something like this:
const myArray = [/* 10000 totally random integers! */];
let pos = 0;
while (pos < myArray.length) {
document.getElementById("unorderedList").innerHTML += `<li>${pos}</li>`;
pos++;
}
console.log("done!");
It freezes the whole window until it finishes, then it logs everything. How can I make it so the loop adds the number every iteration until it finishes instead of finishing the loop then printing everything?
Note: this hypothetical function also needs to interact with a Window
created with window.open
, so I don’t think I can use workers since that interacts with the DOM.
2
Answers
You can use
requestAnimationFrame
.It’s commonly used in animation loops for updating positions and redrawing scenes.
I add sample code below.
Issue
It is due to the browser being busy updating the DOM in each iteration of the loop, and the rendering process is blocking the script execution.
Solution
You can use requestAnimationFrame to break the loop into smaller chunks, which allows the browser to handle rendering between each chunk.