如何在JavaScript中停止失控的setInterval()计时器

时间:2018-03-31 20:56:46

标签: javascript

当我按住鼠标左键并依次按下右键时,

setInterval挂起。之后setInterval不会清除。

    var timer = 0;

    document.getElementById('c_3').onmousedown = function(e) {

          timer = setInterval(function() {myFunction();}, 30);

          if (e.which == 2 || e.which == 3) {

                clearInterval(timer);

          }

    }

1 个答案:

答案 0 :(得分:0)

这就是它现在的运作方式......

    let timer = 0;

    document.getElementById('c_3').onmousedown = function(e) {

      if (e.which == 1) {

        timer = setInterval(function() {myFunction();}, 30);

      }

      if (e.which == 2 || e.which == 3) {

        document.getElementById('c_3').oncontextmenu = function() {

          return false;

        }

        clearInterval(timer);

      }

    }

    document.getElementById('c_3').onmouseup = function() {

        clearInterval(timer);

    }