Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...