简体   繁体   English

清除间隔不适用于javascript计时器

[英]Clear interval not working on javascript timer

Here is my code这是我的代码

 document.addEventListener("keydown", move); function move(e) { switch (e.keyCode) { case 37: x = x - speed; break; case 38: // up key pressed y = y - speed break; case 39: x = x + speed break; case 40: y = y + speed break; case 32: if (iTouched == true) { startCounter(); } break; } sendData(); } document.addEventListener("keyup", getStuff); function getStuff(e) { switch (e.keyCode) { case 32: if (iTouched == true) { shoot(); } break; } } function startCounter() { function count() { time += 1 console.log(time) } interval = setInterval(count, 100) } function shoot() { clearInterval(interval) }

The startCounter() function is triggered by a keydown event listener and the shoot() function is triggered by a keyup event listener. startCounter() 函数由 keydown 事件侦听器触发,而 shot() 函数由 keyup 事件侦听器触发。 For some reason the setInterval will not stop when I lift the key up.出于某种原因,当我抬起键时 setInterval 不会停止。 The shoot() function works with other commands like an alert() just not the clearInterval(). shot() 函数可与其他命令一起使用,例如 alert(),而不是 clearInterval()。 Am I doing something wrong?难道我做错了什么? Thanks!谢谢!

Keydown fires multiple times as you hold down the key.当您按住该键时,Keydown 会触发多次。

 var bod = document.body; bod.addEventListener("keydown", () => console.log('keydown', new Date())) bod.addEventListener("keyup", () => console.log('keyup', new Date()))

So you create more than one interval so you overwrite the last one.所以你创建了多个间隔,所以你覆盖了最后一个。 So you need to clear the interval before you create a new one所以你需要在创建一个新的间隔之前清除间隔

if (interval) clearInterval(interval)
interval = setInterval(count, 100)

or do not create one if it exists或者如果存在就不要创建

if (!interval) {
   interval = setInterval(count, 100)
}

and when you clear it当你清除它时

function shoot() {
  clearInterval(interval)
  interval = null
}

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

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