Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript run a function every quarter hour at 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(); 

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

like image 466
Alex McDaid Avatar asked Mar 21 '13 14:03

Alex McDaid


1 Answers

Get the time of the next even 15 minutes by:

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

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

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

Complete code:

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();
like image 89
kamituel Avatar answered Sep 23 '22 22:09

kamituel