简体   繁体   English

clearInterval() 似乎没有按预期工作

[英]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.我正在开发一个 JavaScript/WebRTC 对讲机应用程序,需要按住一个按钮才能发送音频。 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.它工作正常,直到我在按住左键的同时单击鼠标右键,这导致setInterval function 继续工作并且clearInterval无法通过其 ID 停止它。 It just continues on forever.它只是永远持续下去。 According to everything I have read, clearInterval should stop it, especially if the interval is set globally.根据我读过的所有内容, clearInterval应该停止它,尤其是在全局设置间隔的情况下。

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. clearInterval不起作用。

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.如果您碰巧多次调用创建它的 function,您将有一个不可取消的间隔,因为您将覆盖间隔 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;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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