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

后端 未结 3 856
一生所求
一生所求 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:04

    The next line of your javascript will not run until after the alert box has been dismissed. Instead of using an alert() you could use console.log() which would not pause execution.

    EDIT: My bad, you want the user to see it. As a commenter suggested below, simply change the background color before showing the alert().

    0 讨论(0)
  • 2021-01-20 04:05

    alert() stops the script until dismissed. Try replacing alert() with display() and define display() as:

    function display(a){
        document.getElementById("display").innerHTML = a;
    }
    

    Make sure to have an element in your HTML with id display.

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题