简体   繁体   中英

How to prevent a function from running more than once? - Javascript

i did a game on Javascript, and when you hit an obstacle, the game alerts a message and refreshes the window, the problem is that when you lose, the alert message pops up so many times, how can i limit the number of alerts popping up?

Here's the code:

if (pipes[i].hits(bird)) {
      // console.log("HIT");
      pipes[i].color = "#F00";
      alert("YOU LOST");
      window.location.reload();
}

Where "pipes[ i ]" are the obstacles, "bird" is the character and "hits(bird)" is the function that checks for collision. The point here is that the "alert()" runs like 10 times, how do i stop it?

Thanks in advance ^_^.

Ps: Is there a way to do this without Jquery? I prefer pure Javascript when it comes to simple projects.

I used to have this problem as well, the pipes[i].hitsBird(); function is run multiple times, because you check multiple times, and multiple checks come up true, which prints you lost multiple times, I agree that break; after the code, is the best way for this kind of problem, and if it persists, you might be checking multiple times in the same loop.

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