I am creating a script that draws an ASCII picture. I need to separate each individual character in a tag, though the page gets too laggy and the CPU usage goes up by an extreme amount when executing the loop, the process doesn’t even finish, as it normally would without adding the tag (printing only the characters).
Here is the loop I used:
for(let widthCounter = 0; widthCounter <= 2500; widthCounter++) {
document.getElementById("textMain").innerHTML += ("<span>" + currentScene[widthCounter] + "</span>");
totalCharsDrawn += 1
if (totalCharsDrawn == 100) {
document.getElementById("textMain").innerHTML += "<br>"
}
}
I tried setting a delay for each character with setTimeout()
but it didn’t solve the problem.
2
Answers
First, generate the whole string, then, update the DOM.
I’ve added a timer to compare both approaches.
My code runs 1-2 ms on my system. Your code runs ~1300 ms on my system. Depending on the content of the website, the query and the update can use much time. Even with an almost empty DOM, the factor is >500. Every loop iteration, the browser has to read the whole page, find the ID and rewrite the page. In your case even twice.
I also made this alternative that you can get a DOM-ready object to handle in javascript.
It performs in about 1 to 3 ms, including rendering into the document.
The parsing function includes additional character handling capability, like making spaces solid and ignoring new lines (or making them into breaks).