How to make it alert only once | Sololearn: Learn to code for FREE!


How to make it alert only once

When I get a certain amount of point I want it to alert saying “you win”, but it alerts multiple times how do I fix it

8/19/2022 9:01:03 AM

chase warren

7 Answers

New Answer


When your game is finished, break out of the animation with cancelAnimationFrame. Therefore you need to keep track of the request id/ timestamp. See my comments in the JS tab.


Erm... Lisa solution is right but in game, we hardly cancel the animation frame explicitly. The frame is supposed to be left alone unless it got terminated by a runtime error. If you cancel animation frame and your game is supposed to have a new level, setting things back to their previous state will be difficult as a new frame will be needed, the previous drawing state will be cleared and everything must be redrawn My approach is to create a statemachine depending on the complexity of the game, sometimes I would use a ternary operator to set the game state.. so you can do this inside the loop State = 1; // to be initialised outside loop if (levelCompleted) { If (state == 1) { alert("you won"); // set other variables here next level(); state = 0; }; }; I usually map the numbers as -1: menu 0: completed | idle 1: playing If the state is more than 3, I will use a statemachine


I didn't consider multiple levels! Mirielle I assumed that there was only 1 level (for now) and reaching the points would be the ending state. That's why I approached it by just "cleaning up everything"...


Lisa Exactly 👍


Yeah I understand the approach, I just overthink sometimes due to the game type. Although I can say apart from multiple levels, other reasons why cancelling the frame may be a disaster but I think the most common is the reason I stated. another that seems common is maybe the alert should be detached after every 5secs on completing the game, this also will not be achievable if the frame has been cleared.


Wow awesome game


chase warren If score is always 5, alert will always be called. That's why your game is locked up with the alert. Alternatively, if you want to keep playing, you could just reset your variables. Change the last part to this: if (score >= 5) { alert("you win") score = 0 t = dir = 0 }