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將起作用。
你,因爲它的'var'聲明的作用域'timerseconds'到'click'處理程序,並且'clearInterval'在if語句的後面,所以你需要檢查它。除此之外,縮進代碼使讀取和調試變得更加容易。 – spanky
如果一次點擊開始時間間隔,並且您打算在下次點擊時停止它,它將不起作用,因爲您剛剛用一個新的時間間隔覆蓋了'timerseconds',並且舊時間間隔的引用丟失了,現在它不能停止。 – adeneo