breq
breq

Reputation: 25526

How can I run a JavaScript function at specified times of the day?

I need to run a function every 16 minutes but not when user goes to page, rather at a specific time.

For example: 12:01, 12:16, 12:31, 12:46, 13:01, 13:16, 13:31 and so on...

How do I do that?

updateTodayCharts = setInterval(function () {
    ajax_update( date1 , date2 );
}, 15 * 60 * 1000);

This script runs ajax_update every 15 minutes. When you visit the page at 12:20 it runs at 12:35 (12:20 + 15 minutes).

I need to run this script at 12:36 (so after 11 minutes not 15)

First i will calculate time from now to next update and then set timeinterval time.

Upvotes: 0

Views: 1610

Answers (2)

Jérôme
Jérôme

Reputation: 2090

Check each minute if the number of minutes is 1, 16, 31, 46 or whatever you want but in this case number of minutes modulo 15 must be equal to one :

updateTodayCharts = setInterval(function () {
    var d = new Date(),
        min = d.getMinutes();
    if (min % 15 === 1) ajax_update( date1 , date2 );
}, 60 * 1000);

Upvotes: 0

Paul S.
Paul S.

Reputation: 66394

There are two ways to do this, one is to store last date, have a shorter interval and check enough time has passed, the other is to combine setTimeout with setInterval, or some similar such construction.

var interval = (new Date().getUTCMinutes() + 59) % 15; // current position
interval = 15 - interval;   // remaining til next position
interval = interval * 60e3; // to ms

interval = window.setTimeout(function () {
    interval = window.setInterval(function () {
        ajax_update( date1 , date2 );
    }, 15 * 60e3);
}, interval);

Upvotes: 4

Related Questions