简体   繁体   中英

clearInterval() does not seem to work as expected

I am developing a JavaScript/WebRTC walkie-talkie app and require a button to be held down to send audio. It works fine until I click the right mouse button whilst holding the left which causes the setInterval function to continue working and clearInterval unable to stop it via its ID. It just continues on forever. According to everything I have read, clearInterval should stop it, especially if the interval is set globally.

var intervalId;

$("#transmitbutton").on("mousedown touchstart", function () {
    intervalId = setInterval(function () {
        console.log("PTT pressed");
    }, 1000);
});

$("#transmitcontainer").on("mouseup touchend mouseleave", function () {
    clearInterval(intervalId);
});

I have tried the start and stop buttons and it has the same outcome. clearInterval is not working.

var intervalId;

$("#transmitstart").on("click", function () {
    intervalId = setInterval(function () {
        console.log("PTT pressed");
    }, 1000);
});

$("#transmitstop").on("click", function () {
    clearInterval(intervalId);
});   

If you happen to call your function that creates it more then one time you will have an interval that will not be cancelable since you will overwrite the interval id. So either you need to cancel it, or not make a new interval.

var intervalId;

$("#transmitbutton").on('mousedown touchstart', function() {
  if (intervalId) return; // either exit out and not create a new one
  // if (intervalId) clearInterval(intervalId);  //or remove it here
  intervalId = setInterval(function(){
    console.log("PTT pressed");
  }, 1000);
});

$("#transmitcontainer").on('mouseup touchend mouseleave', function() {
  if (intervalId) clearInterval(intervalId);
  intervalId = null;
});

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