Why don't my alert message and background color change execute simultaneously?

后端 未结 3 855
一生所求
一生所求 2021-01-20 03:36

I\'m trying to get both my final Alert message \"Congratulations...\" and the HTML background color change to happen simultaneously. The color change happens after

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-20 04:13

    There are actually two things going on here. As noted in the comments, Javascript is single-threaded and an alert box waits for your click before executing the next instruction. In your case, one possibility would be to simply change the color before showing the alert box:

                    //CHANGE THE COLOR BEFORE ALERTING
                    document.body.style.backgroundColor = guessedColor;
                    return alert("Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game.\n\nYou can see the color in the background.");
    

    But there is also something else going on here. It looks like even if you fire off the command to change the background color first, the alert box gets fired off before the instruction (to change the color) finishes. An alert box stops the thread in the browser, and that must include the color change instruction as well. I'm not sure if this is a bug or not. And I've only tried it in Chrome, so I'm not sure about other browsers.

    One way you can get around this is to put your alert box on a delayed timer, like this:

      document.body.style.backgroundColor = guessedColor;
      var alertMsg = "Congratulations! You have guessed the color!\n\nIt took you " + guesses + " guesses to finish the game.\n\nYou can see the color in the background.";
      setTimeout(function(){alert(alertMsg)},100);
    

    Here is a working example: https://jsfiddle.net/Lzcht5dz/1/

提交回复
热议问题