Javascript – How to make an HTML element repaint within a Javascript loop

colorsjavascript

I have some Javascript which "animates" a colour change on an HTML element, as follows:

var element = document.getElementById("someid");
while (i < 255) {
    element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')';
    i++;
    slowMeDown(); // This function runs for a few ms to slow the process down
}

As you can see, this changes the color from black to white going through 255 shades of grey in between. I would like to make it visibly "fade" so that the user can see the text gradually disappear.

However, the browser (Chrome and IE – not tested on Firefox yet) only refreshes at the end of the function, so the color simply changes from black to white. Does anyone know how to make the browser repaint during the loop so that I can see the text fade?

Best Solution

function changeColor()
{
    changeColorIncremental(0);
}

function changeColorIncremental(i)
{
    var element = document.getElementById("someid");

    element.style.color = 'rgb(' + i + ',' + i + ',' + i + ')';

    if (i < 255) {
        // Note the 50 millisecond wait below.  Decrease this to speed up
        // the transition, and increase it to slow it down.
        setTimeout('changeColorIncremental(' + (i + 1) + ')', 50);
    }
}