javascript警报和停止执行

时间:2016-12-06 15:51:31

标签: javascript html

这里我们有一个简单的练习javascript游戏,它有一个有效的HTML颜色列表,它在页面加载时选择一个随机颜色,它会询问你猜测并根据你的输入给你提示,当你进入正确的颜色,它会将背景颜色更改为答案的颜色。

当您输入获胜答案时,您会收到警告,告诉您已经赢了,由于某种原因,只有当屏幕上出现警报时按下确定后背景颜色才会改变,即使更改了bg颜色在警报之前。

我的问题是:   (1)关闭警报弹出窗口后为什么BG颜色会发生变化?  (2)在屏幕上出现警报之前,是否有正确的方法使BG颜色发生变化?

function do_game() {
                var colors = ["aqua", "beige", "deeppink" , "coral",  "honeydew", "lime", "gainsboro","rebeccapurple","peru","tan"].sort();
                var answer = colors[Math.floor((Math.random() * colors.length))];
                var finished = 0;
                var numberOfGuesses = 0;
                var myBody=document.getElementsByTagName("body")[0];


                console.log(answer);
                while(!finished){


                var input = prompt('I am thinking of one of these colors \n\n' + colors + '\n\n what color am i thinking of? ' );
                if(input === null) 
                    finished = 1; 
                else{
                    numberOfGuesses++;
                    checkGuess(input);

                    if(input === answer){
                        myBody.style.background=answer;
                        finished = 1;
                        alert('You are right! \n you took ' + numberOfGuesses + ' Guesses!');

                    }
                }

            }

            function checkGuess(input){
                if(colors.indexOf(input) === -1){
                    //does not recognize input
                    alert('I don’t recognize that color!');
                }else if(input > answer){
                    //alphabetically higher
                    alert('Your input is alphabetically higher than mine!');
                }else if(input < answer){
                    //alphabatially lower
                    alert('Your input is alphabetically lower than mine!');
                }
            }
        }

1 个答案:

答案 0 :(得分:2)

在更新DOM的功能运行完毕之前,浏览器不会重新绘制屏幕。

alert正在阻止,因此在您单击“确定”之前阻止该功能继续运行。

alert放入另一个函数中,然后使用setTimeout以非阻塞方式调用它。

document.body.style.background = "blue";
setTimeout(function() {
  alert("Hello");
});