2017-08-25 108 views
2

我试图做一个记录音频和制作的项目,我遇到了这个问题的计时器:setInterval不停止,为​​什么?为什么clearInterval不停止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); 
    } 

}); 

--FIXED--

我加入这个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); 

// 

”。打开音频“是一个打开用户录制对话框的图像,因此当您重新打开它时,clearInterval将起作用。

+4

你,因为它的'var'声明的作用域'timerseconds'到'click'处理程序,并且'clearInterval'在if语句的后面,所以你需要检查它。除此之外,缩进代码使读取和调试变得更加容易。 – spanky

+0

如果一次点击开始时间间隔,并且您打算在下次点击时停止它,它将不起作用,因为您刚刚用一个新的时间间隔覆盖了'timerseconds',并且旧时间间隔的引用丢失了,现在它不能停止。 – adeneo

回答

0

您添加到您的问题的解决方案不健全:这将创建一个新的事件处理程序在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"; 
} 
相关问题