在javascript中是否有更好的睡眠功能方式

时间:2018-01-22 07:15:32

标签: javascript settimeout

祝大家都过得愉快。 我正在为这个项目开发一个游戏,我希望在获胜的情况下它等待2秒才能返回起点我使用这个代码来做

function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
} 

我从这post得到的 无论如何,这个问题是游戏freziz数秒 你可以在这个图片中说it's stuck for 2 seconds 我的问题是有更有效率的方法这样做我也试过setTimeOut()但问题是同样的问题

  

编辑:   这是解决方案很棒,工作完美,非常感谢   from this post

    function sleep (time) {
    return new Promise((resolve) => setTimeout(resolve, time));
    }

sleep(500).then(() => {
// Do something after the sleep!
});

1 个答案:

答案 0 :(得分:0)

为此目的使用setTimeout。

deactivateGame();

setTimeout(function(){

    activateGame()
}, 2000)

在上面的示例中,activateGamedeactivateGame函数会在游戏中放置一些指示符,告诉用户游戏正在等待。