Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run JS function every new minute

So I've got this JavaScript clock I'm working on and I want it to be perfectly synced with the clients' system clock. I know how to get the current time using a Date object and I know how to run the update function every 60000 milliseconds (1 minute). The thing is that the client might load the page when half a minute has already passed, making the clock lag behind with 30 seconds. Is there any way to just run the update function when the minute-variable actually changes? (I only want minute-precision.)

How I get the current time:

var time = new Date();
var currentHour = time.getHours();
var currentMinute = time.getMinutes();

How I run the update function every 60000 ms:

setInterval(update,60000); //"update" is the function that is run
like image 470
Axel K Avatar asked Jun 28 '26 17:06

Axel K


1 Answers

When the user logs in, get the current time and seconds of the minute, subtract 60 to get the remaining seconds, then multiply to set the timer

var time = new Date(),
    secondsRemaining = (60 - time.getSeconds()) * 1000;

setTimeout(function() {
    setInterval(update, 60000);
}, secondsRemaining);
like image 136
tymeJV Avatar answered Jun 30 '26 08:06

tymeJV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!