简体   繁体   中英

JavaScript setInterval only works once

I hope you are doing well. I'm working on a minigame based on JS and want to prevent the user from shooting infinite bullets, so I created this condition. Which only works for the first time and then breaks for the next clicks

also to mention this whole section is inside the loop so shooting works well with or without setInterval

  let shootController = true

  canvas.addEventListener("click", () => {
    if (shootController) {
      //shooting code goes here
      shootController = false;
    }
  });

  if (shootController === false) {
    setInterval(() => {
      shootController = true;
    }, 1000);
  }

Thanks for your replies beforehand

Somehow, I defined the 'setInterval' before and outside the loop and then called that function below and outside. This one WORKS

But from curiosity, I didn't define it at the top as a function and only used it below the loop. This one didn't work.

The problem is solved, but I don't know why.

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