我需要一个高度可靠的计时器/时钟来监控时间,并精确地每5分钟触发一次(实际上是5分钟-1秒,例如xx:59)。它需要异步,因为在5分钟标记处的触发器将调用一个或多个将在后台执行任务的函数。
所以。。。我想出了这个超级简单的程序。我正在寻求反馈。我应该做什么不同的事情吗?这是一个足够可靠的解决方案,可以在生产中使用吗?欢迎提出建议和批评。好的,坏的,或者漠不关心!
**编辑:忘记了这行代码: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);
我可能会将函数定义为一个命名函数,然后在setInterval上调用该函数。可能有相同的性能,但允许您在页面加载或特定操作等时调用它。
function testTime(){
var minuteData,hours,minutes,seconds;
var date = new Date;
hours = date.getHours();
minutes = date.getMinutes();
seconds = date.getSeconds();
//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);
}
setInterval(function() {testTime()}, 1000);