简体   繁体   English

JavaScript setInterval 只工作一次

[英]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.我正在开发一个基于 JS 的小游戏,想要防止用户发射无限子弹,所以我创造了这个条件。 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还要提到这整个部分都在循环内,所以无论有没有 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.不知何故,我在循环之前和外部定义了“setInterval”,然后在下面和外部调用了 function。 This one WORKS这个有效

But from curiosity, I didn't define it at the top as a function and only used it below the loop.但是出于好奇,我没有在顶部定义它为 function ,只在循环下面使用它。 This one didn't work.这个没有用。

The problem is solved, but I don't know why.问题解决了,但不知道为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM