【问题标题】:javascript clearInterval() function is not workingjavascript clearInterval() 函数不起作用
【发布时间】:2021-05-12 06:55:09
【问题描述】:
   var a = 0;

window.addEventListener("keydown", function(e) {
 
  clearInterval(interval) //this dont work
  var interval = setInterval(function() { //this is good
    if (a == 0) {
      console.log(a);
      a = 10;
    } else if (a == 10) {
      console.log(a);
    }
  }, 120)
})

//我希望当用户按下按键间隔停止时,新的间隔重新开始但旧的间隔不能停止

【问题讨论】:

    标签: javascript html reactjs intervals clearinterval


    【解决方案1】:

    你有两个问题。

    • 你有var interval你的函数,所以每次函数运行时它都会reset
    • setTimeout 将在一段时间后调用一次函数。它不会清除间隔,您需要clearInterval

    【讨论】:

    • 你必须解决这两个问题,而不仅仅是其中一个。
    • 您可以更改我的代码并在 cmets 中发布吗?
    • 我照你说的做了,但还是不行
    • 你的函数里还有var interval
    • 如果我用 let 或 const 更改 var,我得到错误
    猜你喜欢
    • 2021-11-29
    • 1970-01-01
    • 2023-04-02
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    相关资源
    最近更新 更多