简体   繁体   中英

How do I stop a runaway setInterval() timer in JavaScript

setInterval hangs when I hold the left mouse button down and sequentially press the right button. setInterval will not clear after that.

    var timer = 0;

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

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

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

                clearInterval(timer);

          }

    }

This is how it works now ...

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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