user15573857
user15573857

Reputation:

Invoke a function after the time changes

I'm curious if you can invoke a function after the time changes?

For example invoking a function after the minute changes maybe something like this:

onMinChange(()=>{console.log('the minute has changed!')})

Note:

I do not mean waiting for a minute to invoke a function like this

setInterval(()=>{console.log('the minute has changed!')},60000);

there's a difference between

invoking a function after the minute changes (Current time 2:30:05, invoke function at 2:31:00 )

&

X waiting for a minute to invoke a function (Current time 2:30:05, invoke function at 2:31:05 )

Upvotes: 0

Views: 50

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074238

There's nothing built into the web platform that will do this (nor, I think, Node.js's standard library). The closest you can come (without some third-party lib) is to get the time, calculate how long it should be until the next minute, and then use setTimeout to schecule a callback. If you want it repeated, repeat as necessary.

Here's an example:

const MINUTE_IN_MS = 60000;
function callNextMinute(fn) {
    const now = Date.now();
    let next = now / MINUTE_IN_MS;
    const ceil = Math.ceil(next);
    if (ceil > next) {
        next = ceil;
    }
    return setTimeout(fn, (next * MINUTE_IN_MS) - now);
}
function tick() {
    console.log(`New minute! Time is ${new Date()}`);
    callNextMinute(tick);
}
console.log(`Started at ${new Date()}`);
callNextMinute(tick);

There, the margin of error is ~10 seconds.

Beware that:

  1. That kind of recurring execution can have an adverse effect on battery life of mobile devices.
  2. Timers are slowed or even stopped for tabs that aren't the active tab in many browsers, so you may well miss the minute if the tab is inactive.

Upvotes: 1

Tobias S.
Tobias S.

Reputation: 23825

You can achieve behaviour like this with the npm package cron.

var job = new CronJob('* * * * *', function() {
  console.log('You will see this message every full minute');
}, null, true, 'America/Los_Angeles');

Upvotes: 0

Related Questions