[英]clearInterval() does not seem to work as expected
我正在开发一个 JavaScript/WebRTC 对讲机应用程序,需要按住一个按钮才能发送音频。 它工作正常,直到我在按住左键的同时单击鼠标右键,这导致setInterval
function 继续工作并且clearInterval
无法通过其 ID 停止它。 它只是永远持续下去。 根据我读过的所有内容, clearInterval
应该停止它,尤其是在全局设置间隔的情况下。
var intervalId;
$("#transmitbutton").on("mousedown touchstart", function () {
intervalId = setInterval(function () {
console.log("PTT pressed");
}, 1000);
});
$("#transmitcontainer").on("mouseup touchend mouseleave", function () {
clearInterval(intervalId);
});
我试过启动和停止按钮,结果相同。 clearInterval
不起作用。
var intervalId;
$("#transmitstart").on("click", function () {
intervalId = setInterval(function () {
console.log("PTT pressed");
}, 1000);
});
$("#transmitstop").on("click", function () {
clearInterval(intervalId);
});
如果您碰巧多次调用创建它的 function,您将有一个不可取消的间隔,因为您将覆盖间隔 ID。 所以要么你需要取消它,要么不做一个新的间隔。
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.