简体   繁体   中英

Sleep, Loop, or What in Javascript?

I have a game loop and it basically is this: function game(){init();setInterval(draw, 30);} but when a player wins I want to call Win() which clears the interval and restart. What's the best way to tackle this in javascript? Since the setInterval() is asynch I've already fallen out of game() by this point. So do I add a busy loop: function game(){while(1){init();setInterval(draw, 30);while(!Win);}} ? There's no good way to sleep() currently is there? Is there a way to call game() inside Win() without making the call stack of arbitrary size? What's the best way to handle this situation?

You can use named interval:

var time;
function game(){
     init();
     time = setInterval(function (){
          draw();
     }, 30);
}

win(){
    if(time){
        clearInterval(time); // clear the interval
        game(); // start the game again.
    }
}

Now you have to call this win function, whenever user wins and start the game.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM