chovy
chovy

Reputation: 75686

how to calcuate seconds left in the current minute of the time

I want to update a clock in the UI when the time changes from 12:01 to 12:02.

I can do a setInterval every 60 seconds, but the beginning might not be on the first second of a new minute. How can I ensure that it starts at the first second?

I think I need to find out how many seconds are left in the current minute and then do a setTimeout that fires setInterval when the seconds elapse.

var secondsLeft = ?; //calculate seconds left in this minute

setTimeout(function(){
    setInterval(function(){
        //update clock
    }, 1000 * 60);
}, secondsLeft);

If moment.js makes it easier, that's fine with me.

Upvotes: 3

Views: 1216

Answers (2)

Petteri H
Petteri H

Reputation: 12232

I would store old value, use requestAnimationFrame to see if browser is ready to render and at the render check if the minute has changed from previous render.

Upvotes: 0

Alex Fitiskin
Alex Fitiskin

Reputation: 775

Try this: secondsLeft = 60 - new Date().getSeconds()

Upvotes: 9

Related Questions