I'm making a game in JS and I'm fairly new to it all. I have created a main loop inside a setInterval, like this:
int = setInterval(() => {
Do game stuff, keyboard input, update sprite positions, etc...
Update the screen
},FPS_interval);
But I want this function to be able to pass control to another function that is also in a setInterval. So when I pass I want to stop the interval trigger on this main function and call the other function on a setInterval. When that function has finished I want to come back to this function, again on a setInterval. I'm trying things like this:
int = setInterval(() => {
Do game stuff, keyboard input, update sprite positions, etc...
If you die, go to game over screen gameOver();
Update the screen
},FPS_interval);
function gameOver(){
clearInterval(int);
int = setInterval(() => {
Do game over stuff
when done, return to main loop.
}, FPS_interval);
}
One issue I have is when the main loop calls the gameOver function, although the gameOver function clears the interval, the main loop continues to execute to the bottom.
Another way of looking at this is I just want to be able to pass between functions, some of them with separate loops, and keep the screen updating at regular intervals.
Is there a cleaner way? I'm sure there must be!
Probably you're looking for a semaphore variable. Try to declare one and once you get in the gameover set that semaphore and in the main set_interval execute istructions after the gameover call only if the semaphore is not setted.