Reputation: 195
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?
Upvotes: 0
Views: 161
Reputation: 74738
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.
Upvotes: 3