2

According to this StackOverflow question

Changing the DOM is synchronous. Rendering the DOM actually happens after the JavaScript stack has cleared.

and according to this google doc the screen fresh rate 60fps is equivalent to roughly refreshing every 16ms, I write this example:

<!DOCTYPE html>
<html>
    <head>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                document.querySelector('#do').onclick = function() {
                    document.querySelector('#status').innerHTML = 'calculating...';
                    // setTimeout(long, 0); // will block
                    setTimeout(long, 1); // will not block
                };

                function long(){
                  let result = 0
                  for (let i = 0; i < 1000; i++) {
                    for (let j = 0; j < 1000; j++) {
                      for (let k = 0; k < 1000; k++) {
                        result += i + j + k;
                      }
                    } 
                  }
                  document.querySelector('#status').innerHTML = 'calculation done';
                  document.querySelector('#result').innerHTML = result.toString();
                }
            });
        </script>
    </head>

    <body>
        <button id='do'> Do long calc!</button>
        <div id='status'></div>
        <div id='result'></div>
    </body>
</html>

with jsfiddle link

I played around with the code and found that blocking happens with time delay under 12ms, and happens more often with lesser delay.

I have two different ways of comprehension:

  1. In this case only setTimeout with time delay over 16ms should not block, time delay of 0 and 1 are way less than 16ms so both of them should block;

  2. Right after setTimeout call and long pushed to message queue (with optional delay), now the call stack is empty so in both cases setTimeout should not block and 'calculating...' always be rendered.

What's wrong with my understanding?

mzoz
  • 1,273
  • 1
  • 14
  • 28

1 Answers1

-1

It's possibly to do with your browser throttling the delay.

It reads as though most browsers disregard a value of 0, might be worth looking at the DOM_MIN_TIMEOUT_VALUE for your browser.

redreddington
  • 408
  • 2
  • 12
  • Thanks reddington that's exactly what I'm looking for! – mzoz Dec 31 '18 at 08:38
  • Please elaborate a bit more on the information provided ad MDN. Without the link your answer does not provide enough information. At least quote the relevant information. – try-catch-finally Dec 31 '18 at 08:49