javascript 每一刻钟在 00、15、30、45 运行一个函数 [英] javascript run a function every quarter hour at 00, 15, 30 ,45

查看:41
本文介绍了javascript 每一刻钟在 00、15、30、45 运行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从堆栈溢出中提取了以下代码:

I have the following code taken from stack overflow:

   function doSomething() {
       var d = new Date(),
       h = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() + 1, 0, 0, 0),
       e = h - d;
       window.setTimeout(doSomething, e);

       //code to be run
       alert("On the hour")
    }
    doSomething(); 

这很完美,每小时都会产生一次警报.我希望该函数每 15 分钟在 00、15、30 和 45 点运行一次

This works perfectly and produces an alert every hour on the hour. I would like the function to run every 15 minutes, at 00, 15, 30 and 45

推荐答案

通过以下方式获取下一个偶数 15 分钟的时间:

Get the time of the next even 15 minutes by:

(d.getMinutes() - (d.getMinutes() % 15)) + 15

例如,当您在 13:43 调用 doSomething() 时,它将在下次 13:45 运行:

On example when you invoke doSomething() at 13:43, it will run next time at 13:45:

( 43 - (43 % 15) + 15 ) = ( 43 - 13 + 15 ) = 45

然后它将按预期运行:14:00、14:15 等等......

Then it will run as expected: 14:00, 14:15 and so on...

完整代码:

function doSomething() {
     var d = new Date(),
         h = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), (d.getMinutes() - (d.getMinutes() % 15)) + 15, 0, 0),
         e = h - d;
     window.setTimeout(doSomething, e);

     console.log('run');
 }
 doSomething();

这篇关于javascript 每一刻钟在 00、15、30、45 运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆