Reputation:
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
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:
Upvotes: 1