How to restart a game

On page load, i have a function say startGame() that runs. The page contains a toggle button, on change startGame() needs to be called again since its the main function containing the API fetch. I believe that doing so will push the newly called startGame() function over the already running one in the call stack. If so, is there any way to terminate the previous function so that it will not cause any inconsistency (JavaScript) ?
5 Replies
AlexCS
AlexCS2w ago
Could you do a conditional and say process.exit() on the startGame that runs onLoad if that has already run and the onChange has been invoked? Or a try catch of some kind?
Reptiloid
Reptiloid2w ago
I don't know exactly how your startGame function is implemented, but you can probably use AbortController to stop it's execution. Here is an example: https://codesandbox.io/p/sandbox/5sv4fr
Harshit Raj
Harshit RajOP2w ago
I am trying to develop a speed typing game whose code looks something like the above. While the goal can be achieved in some way or the other such as rather to restart game, just replace the sentence. But what I am trying to understand is how such games behave? Should a new game or restart game needs to reload the page to create a fresh call stack or is it okay to stack up same function again?
No description
Harshit Raj
Harshit RajOP2w ago
Can use this approach. Thanks I'm not sure if exit will allow me to execute any code afterwards
T3CHN01200
T3CHN012002w ago
How about using a state machine and having your startup code be part of your update loop? It only executes under say the startGame state.

Did you find this page helpful?