0

Here I use the loop code(learned from What's the equivalent of Java's Thread.sleep() in JavaScript?) to simulate web latency to check my loading animation effect. However, the first line is blocked for 5 seconds too. while the second line(the log statement) isn't. What's happening?

  main.innerHTML += '<div id="animation-container"></div>'
  console.log("??????????");

  var e = new Date().getTime() + (5 * 1000);
  while (new Date().getTime() <= e) {}

  main.innerHTML += 'real content'
nichijou
  • 484
  • 4
  • 12
  • 1
    I believe it's because, although the DOM (which is the JS internal representation of the page contents) is updated synchronously, the browser is only able to actually rerender the page when all (synchronous) JS code has finished running. – Robin Zigmond Jan 03 '19 at 10:23
  • 2
    `to simulate web latency to check my loading animation effect` Chrome's (and probably Firefox's) dev tools have this built- in. Don't bother hacking your own code to simulate network latency, use the dev tools ( F12 -> Network -> change "online" to "3G") – Jeremy Thille Jan 03 '19 at 10:26

1 Answers1

1

The browser runs in one single thread (it doesn't, but let's assume that for simplicity). On that thread multiple engines run, one for CSS and HTML and one for JavaScript.

 main.innerHTML += '<div id="animation-container"></div>'
console.log("");

Those two statements got a huge difference: The logging is done by the JavaScript engine, while the DOM mutation gets sent to the HTML engine. Now that sending is asynchronous, as the HTML engine is currently not running as the JavaScript engine is, and therefore the mutation will end up in some sort of queue. Now you block the JavaScript engine, and therefore the browsers thread too, so the HTML engine cannot gain processing time for updating the view.

Conclusion: Don't write blocking JavaScript! Utilize its async nature and the browser tools (DevTools > Latency).

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151