Reputation: 5503
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.
Upvotes: 0
Views: 70
Reputation: 12764
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.
Upvotes: 1
Reputation: 51
You can use setTimeout and style.backgroundColor instead of the functions color() and wait(). I propose this function disco:
function disco(){
var body = document.getElementById("body");
time = 0;
for (var i=0;i<10;i++) // I've put this color to change 10 times, just for test.
{
setTimeout(function(){ body.style.backgroundColor = "red"}, time);
time += 100;
setTimeout(function(){ body.style.backgroundColor = "darkGreen"}, time);
time += 100;
setTimeout(function(){ body.style.backgroundColor = "darkBlue" }, time);
time += 100;
}
}
Upvotes: 0