I believe all the answers are flawed. Once you have started the setInterval, the interval time cannot be changed without creating a new setInterval object. So you will only use the initial calculated time for each iteration.
You can create new setInterval objects, but that has to be costly.
See: How do I reset the setInterval timer?
My recommendation is to create a looping function that utilizes the setTimeout instead.
Here's some code:
var duration = 5; //in minutes. This is just to control the total length
var startTime = new Date().getTime(); //must be in milliseconds
function myOnTheMinuteTimer(){
setTimeout(function(){
var currentTimeMS = new Date().getTime();
var diffMs = Math.abs(startTime - currentTimeMS);
diffMs = diffMs/1000; //take out the milliseconds
var seconds = Math.floor(diffMs % 60);
diffMs = diffMs/60;
var minutes = Math.floor(diffMs % 60);
var minutesLeft = duration - minutes;
console.log("Time passed:", minutes + "m :" + seconds + "s");
if(minutes <= duration){
console.log("Timer expired.");
} else {
myOnTheMinuteTimer();
}
}, setIntervalTimeToNextMinute());
}
//Initialize timer
myOnTheMinuteTimer();
//Get our time until the next minute
function setIntervalTimeToNextMinute(){
var currentDateSeconds = new Date().getSeconds();
if(currentDateSeconds == 0){
return 60000;
} else {
return (60 - currentDateSeconds) * 1000;
}
}
My use case for this was a session timout:
startTime - allows me to pass in any milliseconds time. This way I can avoid lapses in page loading. Say user logins in at a certain time. I capture that time, then pass it into initial function and it will adjust back to the on minute calculation.
duration - I use the duration check for a timeout setting. If the application has a 20 minute timeout, then I need to route the user to the login screen.
optionally - you can add more variations. Say you wish to give the user a 2 minute warning that they will be logged out. Simply add to the conditional an else if for 2 minutes.
Hope that helps! Happy coding!