Reputation: 514
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'
Upvotes: 0
Views: 203
Reputation: 138457
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).
Upvotes: 1