2

In this example:

<div class="test">Lorem Ipsum </div>
<div class="test">Lorem Ipsum </div>
<div class="test">Lorem Ipsum </div>

<button onclick="test();"> click</button>

function test()
{
    $('.test').css("color", "#0f0");

    for(i=0; i<=1000000000; i++)
    {

    }
}

https://jsfiddle.net/t741kz5a/2/

Why does the loop run before the color is changed? And how can I make it work sequentially?

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62

2 Answers2

1

The Browser will only update when not in a function. So it would only update when it exits the function.

You will have to call the loop async, so you first exit the function and then it continues.

function test()
{
    $('.test').css("color", "#0f0");

    setTimeout(function(){
        for(i=0; i<=1000000000; i++)
        {

        }
    }, 1); // in some cases you might have to give it more then just 1 millisecond
}

force DOM redraw with javascript on demand

Community
  • 1
  • 1
CoderPi
  • 12,985
  • 4
  • 34
  • 62
  • Okay, so how update CSS before call for in this function? – user2971916 Nov 25 '15 at 23:39
  • Working for timeout equal 1. But if browser need more time to change CSS still not working... I can't set constant time, becouse i don't know how much time will be needed. – user2971916 Nov 26 '15 at 00:03
  • Use `20` or `50` that should be more then enough. Maybe you saw the link about this problem I posted below the code, and it doesn't look like there is another solution. You will have to put some milliseconds delay on it, sorry. – CoderPi Nov 26 '15 at 00:05
0

The browser will not re-render the screen until a script has finished with the current tick of the processor. A for-loop nags the processor to finish its thread before giving any visual feedback.

But remember that the actual property of the JavaScript DOM has been changed prior to the for-loop in your example, so querying it directly afterwards will show it to be green already.

$('.test').css("color", "#0f0");

console.log( $('.test').css("color") ); // rgb(0, 255, 0);

for (var i = 0; i < 1000000000; i++) { };

In most use-cases, this is acceptable, and shouldn't effect your application.

To simplify: it's not that your element object is not set to its' colour before the loop; it's that the browser has not yet responded to this change visually.

shennan
  • 10,798
  • 5
  • 44
  • 79