gpt4 book ai didi

javascript - 为什么clearInterval没有停止setInterval?

转载 作者:行者123 更新时间:2023-12-01 05:19:34 25 4
gpt4 key购买 nike

我正在尝试为一个录制音频的项目制作一个计时器,在制作过程中,我遇到了这个问题:setInterval 没有停止,为什么?

我有以下代码:

<小时/>
/** Audio **/
var timerseconds = 0;
$('.audio-recorder-dialog-con').on('click', '#record', function() {
gotrecordval = document.getElementById("record").value;

//Crónometro
var timerseconds = setInterval(function() {
rseconds = parseInt(document.getElementById("r-seconds").value);
if (rseconds == 59) {
document.getElementById("r-seconds").value = "00";
}
rseconds = parseInt(document.getElementById("r-seconds").value);
rseconds += 1;
if (rseconds < 10) {
document.getElementById("r-seconds").value = ("00" + rseconds).substr(-2);
}
if (rseconds >= 10) {
document.getElementById("r-seconds").value = rseconds;
}
}, 1000);
//

if (gotrecordval == "Empezar a Grabar Audio") {
document.getElementById("record").value = "Detener/Subir";
}

if (gotrecordval == "Detener/Subir") {
document.getElementById("record").value = "Empezar a Grabar Audio";
$('.audio-recorder-dialog-con').fadeOut(500);
$(".contenido-dialog-new-d").fadeIn(500);
$("#aviaudio").fadeIn(500);
clearInterval(timerseconds);
}

});

--已修复--

我通过将其添加到 setInterval 中来修复它:

//Crónometro
var timerseconds = setInterval(function(){
rseconds = parseInt(document.getElementById("r-seconds").value);
if(rseconds==59){document.getElementById("r-seconds").value = "00";}
rseconds = parseInt(document.getElementById("r-seconds").value);
rseconds+=1;
if(rseconds<10){document.getElementById("r-seconds").value = ("00" + rseconds).substr(-2);}
if(rseconds>=10){document.getElementById("r-seconds").value = rseconds;}

--Code added-
$('html, body').on('click', '.open-audio', function(){
clearInterval(timerseconds);
});
--

}, 1000);

//

“.open-audio”是一个为用户打开录音对话框的图像,因此当您重新打开它时,clearInterval 就会起作用。

最佳答案

您添加到问题中的解决方案并不合理:这将在 setInterval 计时器的每个“滴答”处创建一个新的事件处理程序。这不是正确的做法。

相反,仅在需要启动时才执行 setInterval,因此将其放在第一个 if 中:

if (gotrecordval == "Empezar a Grabar Audio") {
//Crónometro
var timerseconds = setInterval(function() {
rseconds = parseInt(document.getElementById("r-seconds").value);
if (rseconds == 59) {
document.getElementById("r-seconds").value = "00";
}
rseconds = parseInt(document.getElementById("r-seconds").value);
rseconds += 1;
if (rseconds < 10) {
document.getElementById("r-seconds").value = ("00" + rseconds).substr(-2);
}
if (rseconds >= 10) {
document.getElementById("r-seconds").value = rseconds;
}
}, 1000);
//
document.getElementById("record").value = "Detener/Subir";
}

关于javascript - 为什么clearInterval没有停止setInterval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45889209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com