You can slightly reduce the code and make it more accurate, use setTimeout and call the function as close as possible to the next full second. setInterval will drift slowly.
// Return the time to next 5 minutes as m:ss function toNext5Min() { // Get the current time var secs = (new Date() / 1000 | 0) % 300; // Function to add leading zero to single digit numbers function z(n){return (n < 10? '0' : '') + n;} // Return m:ss return (5 - secs/60 | 0) + ':' + z(60 - (secs%60 || 60)); } // Call the function just after the next full second function runTimer() { console.log(toNext5Min()); var now = new Date(); setTimeout(runTimer, 1020 - now % 1000); }
The above is ticking in full minute, so say, 10:00:00, it shows 5:00. If you prefer to show 0:00, then the last line toNext5Min should be:
return (5 - (secs? secs/60 : 5) | 0) + ':' + z(60 - (secs%60 || 60));
Robg source share