I have done a timer from this question's most voted answer. Problem is, that when it reaches 0, it changes date to next day and starts a new 24 hour timer.
Tl;dr 00:00:00 -> 23:59:59 instead of staying 00:00:00 forever.
My current code:
function getTimeLeft() {
var seconds_left = end_time - Math.floor(Date.now() / 1000);
var time_left = new Date(seconds_left * 1000).toISOString().substr(11, 8);
$('#test-time-left').text(time_left);
}
setInterval(getTimeLeft, 1000);
To keep 00:00:00, I thought of 2 ways of solving it.
First (and imho better) would be giving setInterval(getTimeLeft, 1000);
in while
loop with condition seconds_left >= 0
. But I have few problems with that.
I have no idea how to pass variable outside of function.
I don't know if preventing setInterval will do anything, but I might as well just set interval to 0 (ergo turn it off).
Second approach would be simply doing while
inside of function:
while( seconds_left >= 0){
var time_left = new Date(seconds_left * 1000).toISOString().substr(11, 8);
}
Problems:
- Waste resources, because JS script is still being done
@Edit Final result:
function getTimeLeft() {
var seconds_left = end_time - Math.floor(Date.now() / 1000);
if (seconds_left <= 0)
{
seconds_left = 0;
clearInterval(timer);
}
var time_left = new Date(seconds_left * 1000).toISOString().substr(11, 8);
$('#test-time-left').text(time_left);
}
var timer = setInterval(getTimeLeft, 1000);
I also set seconds_left to 0 just in case script miss 0 second frame (for example user closes browser while countdown happen).