2017-06-06 18 views
1
頁面

我有此Javascript倒計時器完美的作品。唯一的問題是我只能在一頁中使用它一次。我想多次使用它。的Javascript計時器使用多次在

我覺得劇本使用id ="timer"這就是爲什麼我不能夠多次使用它。

下面是JS代碼:

<script> 
var startTime = 60; //in Minutes 
var doneClass = "done"; //optional styling applied to text when timer is done 
var space = '  '; 

function startTimer(duration, display) { 
    var timer = duration, 
    minutes, seconds; 
    var intervalLoop = setInterval(function() { 
    minutes = parseInt(timer/60, 10) 
    seconds = parseInt(timer % 60, 10); 
    minutes = minutes < 10 ? "0" + minutes : minutes; 
    seconds = seconds < 10 ? "0" + seconds : seconds; 
    display.textContent = "00" + space + minutes + space + seconds; 
    if (--timer < 0) { 
     document.querySelector("#timer").classList.add(doneClass); 
     clearInterval(intervalLoop); 
    } 
    }, 1000); 
} 

window.onload = function() { 
    var now = new Date(); 
    var hrs = now.getHours(); 
    var setMinutes = 60 * (startTime - now.getMinutes() - (now.getSeconds()/100)), 
    display = document.querySelector("#timer"); 

    startTimer(setMinutes, display); 
}; 
</script> 
+1

那麼,什麼是您的編碼問題?一個好的開始是將全局變量放入函數中。考慮使用構造函數來創建實例,或者使用閉包來保持變量對每個定時器的調用都是「私有的」。 – RobG

+0

是的,包裝計時器相關的東西在功能 - 這就是解決方案。使它像一個原型,所以你可以讓 – DanilGholtsman

+0

@RobG從他的代碼和他的問題來看,我不知道OP在這種編碼的水平,現在它的實例。 –

回答

0

只是聲明intervalLoopstartTimer功能,它會在全球上市。

var intervalLoop = null 

function startTimer(duration, display) { 
    intervalLoop = setInterval(function() { .... } 
}) 


function stopTimer() { 
    clearInterval(intervalLoop) // Also available here! 
}) 
0
window.setInterval(function(){ Your function }, 1000); 

這裏1000意味着timer 1 sec

0

我覺得這樣的事情可能會有所幫助:

Timer對象聲明

var timerObject = function(){ 
 
\t this.startTime = 60; //in Minutes 
 
\t this.doneClass = "done"; //optional styling applied to text when timer is done 
 
\t this.space = '  '; 
 

 
    \t return this; 
 
}; 
 

 
timerObject.prototype.startTimer = function(duration, display) { 
 
    var me = this, 
 
    timer = duration, 
 
    minutes, seconds; 
 
    var intervalLoop = setInterval(function() { 
 
    minutes = parseInt(timer/60, 10) 
 
    seconds = parseInt(timer % 60, 10); 
 
    minutes = minutes < 10 ? "0" + minutes : minutes; 
 
    seconds = seconds < 10 ? "0" + seconds : seconds; 
 
    display.textContent = "00" + me.space + minutes + me.space + seconds; 
 
    if (--timer < 0) { 
 
     // not sure about this part, because of selectors 
 
     document.querySelector("#timer").classList.add(me.doneClass); 
 
     clearInterval(intervalLoop); 
 
    } 
 
    }, 1000); 
 
}

使用它像

var t1 = new timerObject(); 
var t2 = new timerObject(); 
t1.startTimer(a,b); 
t2.startTimer(a,b); 

JS小提琴例如:

UPD1評論部分,因此定時器可以停止

https://jsfiddle.net/9fjwsath/1/

+0

感謝您的回答。你能告訴我var t1和t2怎麼工作。 目前在HTML我只是使用'<跨度ID = 「計時器」>'。這將如何工作? –

+0

@SahibjotSingh哦,所以你想使用它,應用到相同的HTML元素? – DanilGholtsman

+0

如果這是如何工作。那太好了。我在改變id或使用類方面沒有問題。但我需要在一些HTML元素中使用它們。 –