javascript - 每 5 分钟触发一次的计时器

标签 javascript performance datetime optimization

我需要一个高度可靠的计时器/时钟来监控时间,并精确地每 5 分钟触发一次(实际上是 5 分钟 -1 秒,例如 xx:59)。它需要是异步的,因为 5 分钟标记处的触发器将调用一个或多个将在后台执行任务的函数。

所以...我想出了这个 super 简单的例程。我正在寻找反馈。我应该做一些不同的事情吗?这是一个足够可靠的解决方案,可以在生产中使用吗?欢迎提出建议和批评。好,坏,或者无所谓!

**编辑:忘记了这行代码: 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);

关于javascript - 每 5 分钟触发一次的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38547770/

相关文章:

c# - 使用 EF 使用 sum 进行慢速 mysql 查询

Python 和 MySQL——在 3 秒内查找所有行

angular - 如何在 Angular 8 生产版本上压缩文件

mysql - 将日期和时间与日期时间列分开,并将每个日期和时间放入其自己的日期和时间列中

PHP `DateTime::days` 返回垃圾?

php - javascript 和 php 验证?

javascript - 显示大型列表的最佳实践

javascript - javascript 中的圆括号 () 放置 - 不寻常的语法?

javascript - 在同一浏览器中打开新选项卡时如何关闭选项卡?

mysql简单查询花费较长时间