fiskeboss fiskeboss - 1 month ago 10
Javascript Question

Chrome repaint DOM during JavaScript execution

I am creating a course for people who have never done programming, and would like to demonstrate basic DOM-manipulation without using async programming or callback functions.

I thought I could do something like this:

function color(element, color) {
element.style = "background: " + color + ";";
}

function wait(milliseconds)
{
var e = new Date().getTime() + (milliseconds);
while (new Date().getTime() <= e) {}
}

function disco() {
var body = document.getElementById("body")
color(body, "red")
wait(500)
color(body, "darkGreen")
wait(500)
color(body, "darkBlue")
}

disco()


This runs fine, but the UI doesn't refresh until the end, so the background never turns red or green - it just ends up blue.

Is there any way to force a repaint during the execution of the function?

I am aware that this not a good idea or even acceptable for an actual implementation, but my aim is to keep things comprihensible to newbies.

Answer

While you do your busy waiting, the browser cannot do anything else. This approach is seriously not recommended. Instead, you can set up your disco like this.

var body = document.body;
var colors = [ "red", "darkgreen", "darkblue" ]; 
var nextColor = 0;

function color(element, color) {
    element.style = "background: " + color + ";";
}

function setNextColor() {
  color(document.body, colors[nextColor%color.length];
  nextColor = nextColor + 1;
}

function disco() {
    setInterval(setNextColor, 500);        
}

Please note that this code is only for demonstration of the technique, not tested in any ways.

Comments