-1

I wish you all having a great day. I am working on this project for a game and I want in case of winning that it waits for 2 seconds before returning to the start point I using this code to do just

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

which I got from this post anyhow , the problem with this is that the game freziz for the number seconds you can say in this picutre it's stuck for 2 seconds My question is is there is more effichent way to do so I have tryied also setTimeOut()but it's the same problem

EDIT : This Is the Solution is great and work perfectly, Thanks a lot from this post

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

sleep(500).then(() => {
// Do something after the sleep!
});
OnlySalman
  • 112
  • 1
  • 12
  • For a game you don't want the waiting time to block all of your UI (the freeze you are talking about), so your sleep needs to be somehow asynchronous. It's something to keep in mind for the overall architecture of your pgrogram. Without understanding the architecture of your app, it's hard to guide you correctly. Namely, you don't provide a [mcve] that shows this freeze so we can work on. – Pac0 Jan 22 '18 at 07:17
  • The 2nd answer in the [linked post](https://stackoverflow.com/a/1141340/797194) pretty much sums up why you cannot have non-freezing "sleep" in JavaScript. – m90 Jan 22 '18 at 07:19

1 Answers1

0

Use setTimeout for this purpose.

deactivateGame();

setTimeout(function(){

    activateGame()
}, 2000)

In the above example, the activateGame and deactivateGame functions will place some indicators over your game to tell the user that the game is waiting.

Charlie
  • 22,886
  • 11
  • 59
  • 90