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

时间:2019-02-13 22:50:18

标签: javascript

这是我的代码

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)
}

startCounter()函数由keydown事件侦听器触发,而Shoot()函数由keyup事件侦听器触发。出于某种原因,当我抬起琴键时,setInterval不会停止。 Shoot()函数可与其他命令(例如alert())一起使用,而不能与clearInterval()一起使用。难道我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:2)

按下键时,多次按下键。

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

因此,您创建了多个间隔,因此覆盖了最后一个间隔。因此,您需要在创建新间隔之前清除间隔

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

或者如果存在则不创建一个

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

当您清除它时

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