簡體   English   中英

JavaScript重復倒數計時器至正午

[英]Javascript repeating countdown timer to midday

我正在嘗試創建一個JavaScript倒數計時器,以顯示小時和分鍾,每天倒計時至中午。 到達中午時,我希望計時器重置並再次開始倒計時至中午(顯然要倒數至第二天)。

我有下面的代碼,但是我只是無法使其正常工作,中午后代碼可以正常工作,但是一旦達到午夜,計數就不正確了。

這是我的代碼:

function ShowTimes() {
    var now = new Date();
    var hrtime = now.getHours()
    var hrs = 23 - hrtime + 12;
    var mins = 59-now.getMinutes();
    var secs = 59-now.getSeconds();
    var str = '';
    str += hrs+' hours '+mins+' minutes';
    document.getElementById('countdown').innerHTML = str;
}

var _cntDown;

function StopTimes() {
    clearInterval(_cntDown);
}

任何幫助深表感謝! 提前致謝。

更改小時數計算邏輯,如下所示:

if(hrtime>12)
    hrtime=23- hrtime+ 12;
else
    hrtime= 12-hrtime;

您是否居住在春季/秋季將時鍾向前/向后移動的地方?

如果是這樣,那么一年中您將有兩天的時間和分鍾邏輯將失敗。

即使時鍾改變,這也是一種可行的方法:

var now = new Date();
var midday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (now.getHours() >= 12 ? 1 : 0), 12);
var millisToMidday = midday.getTime() - now.getTime();
var hours = Math.floor((millisToMidday / (60 * 60 * 1000)))
var minutes = Math.floor((millisToMidday / (60 * 1000))) % 60;
var seconds = Math.floor((millisToMidday / (1000))) % 60;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM