gpt4 book ai didi

Javascript 倒数计时器不会停在零,也不会在给定时间重新启动

转载 作者:行者123 更新时间:2023-11-30 20:15:57 25 4
gpt4 key购买 nike

我的用例如下:

我需要我的倒计时时钟来查看本地机器时间,确定离就寝时间还剩多少时间,以及bt(就寝时间)停止

在 UI 上,它应该直观地显示 00:00:00

然而,一旦本地机器时间与wt(唤醒时间)相同,它应该重新开始倒计时,直到bt(就寝时间)。

这应该一遍又一遍地重复。

另一个注意事项是应用程序可能未运行(即浏览器可能已关闭)并且脚本可能无法满足以下if条件:

if (小时 === 0 && 分钟 === 0 && 秒 === 0)

我将如何缓解这种情况?

我写了下面的代码:

    $(document).ready(function () {

var bt = "23:00";
var dat = "10:00";
var wt = "08:00";

console.log('Bed Time:' + bt);
console.log('Daily Available time' + dat);
console.log('Wake up time:' + wt);

placeHolderDate = "Aug 18, 2018 " + bt;
var countDownDate = new Date(placeHolderDate).getTime();


var countDownHourMin = (wt.split(":"));


// Update the count down every 1 second
var x = setInterval(function () {

// Get todays date and time
var now = new Date().getTime();

// Find the distance between now and the count down date
var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);

$("#countDown").val(hours + "h " + minutes + "m " + seconds + "s ");

// If the countdown is over, write some text
if (hours === 0 && minutes === 0 && seconds === 0) {
//clearInterval(x);
$("#countDown").val("00:00:00");
}

if (hours < 0 || minutes < 0 || seconds < 0) {
// clearInterval(x);
$("#countDown").val("00:00:00");
}

console.log(hours + "h " + minutes + "m " + seconds + "s ");

}, 1000);


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="countDown"></p>

代码似乎可以工作,但存在一些问题。倒计时变为负数(这可能没问题,只要我可以简单地利用它来实现我的功能),并且时钟在到达 00:00:00wt(唤醒时间)已到。

最佳答案

对日期/时间对象之间的差异进行模运算将为您提供日期/时间下一次时钟将显示该时间。

模数是除法的其余部分。让我们用 24 小时的简化示例来说明这一点:

第二天是 13:00。

第 3 天的 15:00 有一个闹钟。与现在的区别是 (15-13 + (3-2)*24) = 26。26 模 24 的结果是 2,可以将其视为 26/24 = 1 rest 2

现在我们在第 1 天的 12:00 有一些闹钟日期。与现在的区别是 (12-13 + (1-2)*24) = -25。-25 模 24 的结果是 23,因为 24 的下一个小倍数是 -48 而 -25-(-48) 是 23。

不幸的是,JavaScript 不支持对负数进行真正的模运算开箱即用的数字。 % 运算符做类似的事情,它产生无符号值的模。但是,您可以轻松实现自己真正的取模方法:

  (dividend % divisor) + divisor) % divisor

其实我们计算的不是小时,而是毫秒,所以我们取每天的毫秒数作为除数。因此,每天以毫秒为模的两个日期之差将为您提供毫秒数,直到时钟显示Date 对象中包含的时间组件。我们将其添加到当前时间并获得下一个闹钟时间。这样我们就可以比较 Date 对象并计算与当前时间的差异。

此外,浏览器中的日期还存在一些问题。定时器功能不能准确工作。您可能会遇到 setInterval() 的漂移。我在 Firefox 上对此进行了测试,每次几毫秒后都会触发 inverval。这会迅速累积成秒和分钟。

作为解决方法,我们可以使用 setTimeout() 并根据当前时间计算下一整秒的触发时间,但是,回调可能会过早触发几毫秒。因此我们不能依赖 Date 对象的 getSeconds()。由于这个事实,我们需要实现一个近似值,将四舍五入为整秒或 1/100 秒。

我们可以扩展Date对象的原型(prototype)来提高可用性。

$(() =>
{
const
millisecondsPerDay = 1000*60*60*24,
milliSecTolerance = 0, // timer functions in browser do not work exactly
clockPrecision = 10, // timer functions in browser do not work exactly, round to 10 millisec.
emptyTimeString = new Date().toLocaleTimeString().replace(/\d/g, '-') // e.g. '--:--:--';
;


// Since JavaScript % operator does not work propperly on neg. numbers, we want a true Modulo operation.
// 23 mod 10 = 3 (correct); -23 mod 10 = 7 (means 7 more than -30, %-op gives 3)
// We could do that in a Number prototype method:
Object.defineProperties(Number.prototype,
{
mod : { value: function(n) { return ((this%n)+n)%n; } }
});


function lowerPrecision(operand, precision)
{
if(void 0 === precision)
precision = clockPrecision;
let result = Math.round(operand.valueOf() / precision)*precision;
return Date.prototype.isPrototypeOf(operand) ? new Date(result) : result;
}

// Let's extend the Date object to make it more handy
Object.defineProperties(Date.prototype,
{
toUTCTimeHMS : { value: function() { return this.toUTCString().match(/(.{8}) GMT/)[1];; }},

setFormattedTime : { value: function(timeString)
{
this.setHours(...timeString.split(/[:.]/));
return this; // support chaining
}},

getApproximateDate : { value: function(precision)
{
if(void 0 === precision)
precision = clockPrecision;
return lowerPrecision(this, precision);
}},

getApproximateTime : { value: function(precision) { return this.getApproximateDate().getTime(); } },

// Returns the next date/time when the time component will be reached
nextDailyTimeDate : { get : function()
{
let now = Date.getApproxNow();
return new Date(now + (this-now).mod(millisecondsPerDay));
}},
});


// Timers do not work accurately. The might execute even some milliseconds too early.
// Let's define a custom functional now-property that gives an approximated value in steps of some milliseconds.
Object.defineProperties(Date,
{
getApproxNow : { value: (precision) => lowerPrecision(Date.now(), precision) },
getDateApproxNow : { value: (precision) => new Date().getApproximateDate(precision) },
});


// ===================================================================================


var
nextTick,
alarms = []
;


function Alarm(tr, collection)
{
let
$tr = $(tr) ,
input = $tr.find('td>input')[0],
th = $tr.find('th' )[0],
tdRemaining = $tr.find('td' )[1]
;

Object.defineProperties(this,
{
tr : { get: () => tr },
th : { get: () => th },
input : { get: () => input },
remaining : { get: () => tdRemaining },
collection: { get: () => collection },
});

this.update();
this.registerEvents();
}


// shared prototype doing all the stuff
Alarm.prototype = new function()
{
Object.defineProperties(this,
{
update : { value: function ()
{
this._nextDate = new Date().setFormattedTime(this.input.value).nextDailyTimeDate;
this.collection.updateDisplay();
}},

nextDate :
{
get: function() { return this._nextDate; },
set: function(value)
{
let date;
switch(Object.getPrototypeOf(value))
{
case Date:
date = value;
break;
case String.prototype:
date = new Date().setFormattedTime(value);
break;
case Number.prototype:
date = new Date(value);
break;
default:
return null;
}
this._nextDate = date.nextDailyTimeDate;
this.input.value = this._nextDate.toLocaleTimeString();
}
},
registerEvents : { value: function() { $(this.tr).find('input').on('change', (ev) => { this.update(); }); }},
valueOf : { value: function() { return this._nextDate } },
remainingTime : { get : function() { return new Date(this._nextDate.getApproximateTime()); } },
updateDisplay : { value: function()
{
this.remaining.innerText = this === this.collection.nextAlarm
? new Date(this.remainingTime - Date.getDateApproxNow()).toUTCTimeHMS()
: emptyTimeString
;

if(this._nextDate.getApproximateTime() > Date.getDateApproxNow())
return;

this.update();
return true;
}},
});
};


Object.defineProperties(alarms,
{
updateDisplay : { value: function()
{
let changed = false;
do for(let i in this)
if(changed = this[i].updateDisplay())
break;
while(changed); // refresh display of all alarms when any data has changed while processing
}},

nextAlarm : { get : function()
{
return this.length
? this.reduce((acc, cur) => cur.nextDate<acc.nextDate ? cur:acc)
: null
;
}},
});


$('#alarm-table tr:nth-child(n+2)').each( (i, tr) =>alarms[i] = new Alarm( tr, alarms ) );


function onTick()
{
alarms.updateDisplay();
}


(function tickAtFullSeconds()
{
onTick();
nextTick = setTimeout(tickAtFullSeconds, milliSecTolerance + 1000 - new Date().getMilliseconds());
})();




$('#test-button').click((ev) =>
{
time = Date.now();
alarms.forEach(i=>i.nextDate = (time += 5000));
});
window.alarms = alarms; //DEBUG global access from browser console
});
tr:nth-child(n+2)>th
{
text-align: left;
background-color: silver;
}
td
{
background-color: lightgray;
}
th
{
background-color: grey;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Alarm</title>

<link rel="stylesheet" href="AlarmTimer.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>



<body>
<h1> Alarm Timer </h1>
<h2 id="message"></h2>
<table id="alarm-table">
<tr>
<th>Alarm</th>
<th>Time</th>
<th>Remaining</th>
</tr>
<tr id="waking-up-time">
<th>waking-up time</th>
<td class="time" ><input type="time" step="1" value="07:15:00"></td>
<td class="remaining"> --:--:--</td>
</tr>
<tr id="noon-hour">
<th>noon hour</th>
<td class="time" ><input type="time" step="1" value="12:00:00"></td>
<td class="remaining"> --:--:--</td>
</tr>
<tr id="bed-time">
<th>bed time</th>
<td class="time" ><input type="time" step="1" value="22:00:00"></td>
<td class="remaining"> --:--:--</td>
</tr>
</table>

<button id="test-button">set test times</button>

</body>
</html>

关于Javascript 倒数计时器不会停在零,也不会在给定时间重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51918480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com