【发布时间】:2016-07-24 10:50:29
【问题描述】:
我需要一个高度可靠的计时器/时钟来监控时间,并精确地每 5 分钟触发一次(实际上是 5 分钟 -1 秒,例如 xx:59)。它需要是异步的,因为 5 分钟标记处的触发器将调用一个或多个将在后台执行任务的函数。
所以...我想出了这个超级简单的例程。我正在寻找反馈。我应该做一些不同的事情吗?这是在生产中使用的足够可靠的解决方案吗?欢迎提出建议和批评。好,坏,或无所谓!
**EDITED:忘记了这行代码:
minutes = ( mminutes < 10 ? "0" : "" ) + mminutes;
var minuteData,hours,minutes,seconds;
setInterval(function() {
var date = new Date;
hours = date.getHours();
mminutes = date.getMinutes();
seconds = date.getSeconds();
minutes = ( mminutes < 10 ? "0" : "" ) + mminutes;
//get the second digit of minutes
minuteData = minutes.toString()[1];
console.log(minuteData);
//test if at time x4:59 or x9:59, hence 1 sec before the 5min interval
var trigger = ((seconds == 59 && (minuteData == "9" || minuteData == "4")) ? true : false);
console.log(trigger);
//trigger is just a proxy for a task that will be called
}, 1000);
【问题讨论】:
-
这不会是“精确的”......它可能会在 x:x[49]:59.0 或 x:x[49]:59.999 触发 - 几乎是第二个差异
-
如果页面失去焦点,您会发现这是非常不准确的。我认为 requestAnimationFrame 可能会有所帮助,但它没有
标签: javascript performance datetime optimization