Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does alert appear before background changes?

So, I've been trying stuff lately and got this piece of code in my script:

document.body.bgColor = "red";
alert("hello");

But in Chrome, the alert dialog pops up first and only after I close it does the background of my body changes. In Firefox, I get the expected behaviour with body background changing to red followed by the popup.

I know we shouldn't rely on alerts and similar browser controls but can anyone tell me if this is happening because the behaviour is not in the standards or if it's because my understanding of synchronous execution of the above code is wrong?

like image 309
sangeeth96 Avatar asked Dec 03 '16 07:12

sangeeth96


People also ask

Why does alert pop twice?

You can blame the default Repeat Alerts setting in iOS for this. This is set to repeat alerts once for the Messages app, meaning you'll get a second alert for the same message two minutes after the first one. To avoid this repeated alert, you need to mark the message as read.

Why do we use alerts?

It is mostly used to give a warning message to the users. It displays an alert dialog box that consists of some specified message (which is optional) and an OK button. When the dialog box pops up, we have to click "OK" to proceed.


1 Answers

The rendering process has a lifecycle of it's own and does not block the javascript thread. They both work independently.

The solution is to "pause" the JavaScript execution to let the rendering threads catch up. This can be done via a simple setTimeout set to 0

document.body.style.backgroundColor = "red";

setTimeout(function() {
  alert("hey");
}, 0)

Note that bgColor has been deprecated since 2003 with the DOM Level 2 Spec. The current way to set the background color of an element is via element.style.backgroundColor.

like image 178
marvinhagemeister Avatar answered Nov 15 '22 19:11

marvinhagemeister