What's the logic behind order of JS code execution? I'd expect after clicking the button the background to become red and THEN the message to show up. However, the message is appearing first and color is applied to background after I click OK -> CodePen. What would be proper&correct way to make the background red BEFORE I click OK?
function run(){
document.body.style.backgroundColor = 'red';
alert('Contratulations!');
}
<html>
<head></head>
<body>
<button onclick="run()">Click me!</button>
</body>
</html>
The code is executed in the order you expect, however, each of those statements is not synchronous, as they invoke funcitonality provided by the Webbrowser.
Browser executed Javascript does not occur on the UI Thread. So when you change the DOM (the abstraction that allow Javascript to interact with browser HTML), it instead triggers an update to the UI (Browser page) which occurs separate from javascript execution. The underlying DOM element is updated, but there is a non instantaneous update to the actual UI.
In your code, after you change the DOM element, the code then immediately triggers the browser to display an Alert. Displaying alerts is a browser specific behavior, and in the case of Chrome, it pauses the UI update, and requires you to interact with the alert before continuing. In Firefox, the Alert is shown after the UI is updated.
The behavior between the two browsers is simply a difference in how the browser rendering engine and event loops are implemented.
function run(){
document.body.style.backgroundColor = 'red';
setTimeout(function() {
alert('Contratulations!');
},0 );
}
<html>
<head></head>
<body>
<button onclick="run()">Click me!</button>
</body>
</html>
This answer has a little more information on how you can solve the problem, Why is setTimeout(fn, 0) sometimes useful?
By calling setTimeout
you are adding the alert
display to the end of the javascript event loop, which gives the UI enough time to update.