2017-03-16 2043 views
0

請在moment.js中實施24小時倒數計時器,我需要幫助。這裏是我的代碼:使用Moment.js實現24小時倒數計時器

<script> 
window.onload = function(e){ 

var $clock = $('#clock'), 

duration1 = moment.duration({ 
    'seconds': 30, 
    'hour': 0, 
    'minutes': 0, 
    'days':0 
}); 
duration2 = moment.duration({ 
    'seconds': 60, 
    'hour': 0, 
    'minutes': 0, 
    'days':0 
}); 

diff=duration2-duration1; 
duration=moment.duration(diff, 'milliseconds'); 


interval = 1000; 
setInterval(function(){  
    duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');    
    $('#clock').text(duration.days() + 'd:' + duration.hours()+ 'h:' + duration.minutes()+ 'm:' + duration.seconds() + 's');  
}, interval); 
</script> 

問題是我刷新頁面的任何時候定時器刷新也。我如何解決這個問題。如果有更好的方法來實現這一點,請分享。

感謝

+0

您可以從頁面加載時起24小時內計時器倒數,也可以向預定的時間點向下計數;這聽起來像你想要後者。如果是這樣,你至少需要在你的代碼的某個地方有時間戳 – Aron

+0

你好阿隆,我將如何創建時間戳,以便它從當前時間創建一個24小時的郵票 –

+0

請參閱我的答案。它回答你的問題嗎? – Aron

回答

0

這是我會怎麼做:

// create the timestamp here. I use the end of the day here as an example 
const end = moment().endOf('day'); 

setInterval(function() { 
    const timeLeft = moment(end.diff(moment())); // get difference between now and timestamp 
    const formatted = timeLeft.format('HH:mm:ss'); // make pretty 

    console.log(formatted); // or do your jQuery stuff here 
}, 1000); 

這將打印一個時間戳每秒這樣的:

09:49:25 
09:49:24 
09:49:23 
09:49:22 
... 
+1

從這我可以設置我想要的時間作爲它的時間戳和倒計時。謝謝阿隆。 –

+0

非常好,如果我的答案有幫助,請將它標記爲接受:) – Aron

+1

絕對會這樣做 –

0

你可以使用localStorage保存原始時間戳。另一種選擇是將其保存在服務器上(數據庫?)。無論哪種方式,如果刷新頁面,您仍然會同時倒計時。

+0

哈利,如果我確實保存服務器上的時間戳,我將如何爲用戶分配唯一的計時器(假設他們單擊按鈕)。 –

+0

現在又回到了在客戶端的localStorage(或cookie)中保存某種id。 –