3

I am trying to understand the blocking nature of javascript code. I understand javascript is single threaded. So we have to use timers and callbacks for some features.

In this case, I have a loop that is changing the background color. It doesn't change the bg color until the loop ends. Why? Why can't the browser just update the document color?

<script>

 $(document).ready(function(){
    console.log('hi')

    var x = 0;
    var color = 'red';

    while (x< 10000000) {
        x+= 15 ;
        document.body.style.background = color;
    }

});
</script>
runners3431
  • 1,425
  • 1
  • 13
  • 30

2 Answers2

0

The problem is that the repaint browser process will not by trigger until your loop ends. This process is the one in charge to apply visibility changes to DOM. You can try wrapping your code inside a setTimeout function. It will delay your execution time but I think it will repaint flows:

while (x< 10000000) {
  setTimeout(function() {
    x+= 15 ;
    document.body.style.background = color;
  }, 100);
}
ianaya89
  • 4,153
  • 3
  • 26
  • 34
  • So with blocking processes like a while loop, any visible changes to the dom will not update until after it exits the loop? – runners3431 Oct 13 '16 at 14:30
  • Yes, that is the expected behavior. http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/ – ianaya89 Oct 13 '16 at 14:33
0

Dom operations will be pushed to stack and should start pulling it at end of execution and in your case changing the background color is the first Dom operation in stack so once while is done, changing background color operation will be pulled and effect.

mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51