Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading