最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why does alert appear before background changes? - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Dec 3, 2016 at 7:55 runofthemillgeekrunofthemillgeek 1,2321 gold badge12 silver badges20 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 12

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.

The simplest workaround will be like:

document.body.bgColor = "red";
setTimeout(function() {
        window.alert('Hello There!');
    },  10);

The timeout value "9" is the minimum in my case, if i use <9, alert appears first.

You most likely can enforce the background color to change before dialog popping up by yielding for a short time before opening the alert thus allowing the browser to repaint.

setTimeout(function () { alert("hello"); }, 1);
发布评论

评论列表(0)

  1. 暂无评论