为什么clearInterval没有停止setInterval?

时间:2017-08-25 20:48:41

标签: javascript jquery

我试图为一个记录音频的项目制作一个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);

//

&#34;。开 - 音频&#34;是一个打开用户录制对话框的图像,因此当您重新打开它时,clearInterval可以正常工作。

1 个答案:

答案 0 :(得分:0)

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

相反,只有在你需要启动时才执行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";
}
相关问题