繁体   English   中英

为什么clearInterval不停止setInterval?

[英]Why clearInterval is not stopping setInterval?

我正在尝试为录制音频的项目制作一个Timer,而在制作过程中,我遇到了这个问题: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";
}

暂无
暂无

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

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