Why does alert appear before background changes?

前端 未结 3 1584
长发绾君心
长发绾君心 2020-12-11 17:14

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

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

But in Chrom

相关标签:
3条回答
  • 2020-12-11 17:43

    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.

    0 讨论(0)
  • 2020-12-11 17:43

    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.

    0 讨论(0)
  • 2020-12-11 18:09

    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 讨论(0)
提交回复
热议问题