Rei Rei - 7 months ago 14
Javascript Question

JQuery Countdown timer not counting if page closed

i have problem with my countdown i can store timer in local storage, but if i closed the page, the timer not counting and if i open the page again timer start counting again. How to make timer still counting when i close the page and open it again. I am using keith-wood countdown

This is my code

$(function () {
var temporary=3600;
if (window.localStorage.getItem("detik")!=null)
{
temporary=window.localStorage.getItem("detik");
}
else {
window.localStorage.setItem("detik",temporary);
}
$('#defaultCountdown').countdown(
{
until:+temporary,
compact: true,
onExpiry: end,
onTick:function(e)
{
var detik=(e[4]*3600)+(e[5]*60)+e[6];
window.localStorage.setItem("detik",detik);
}});
});

function end() {
alert('We have lift off!');
}


Thank You and Cheers!!

Answer

Well, you can't expect your javascript to continue counting down when your page is closed. So instead of saving the seconds left, you should save the timestamp on which your timer will reach 0.

var reachZeroOn;
if (window.localStorage.getItem("reachZeroOn") !== null) {
    reachZeroOn = new Date(window.localStorage.getItem("reachZeroOn"));
} else {
    reachZeroOn = new Date((new Date).getTime() + 3600000);
    window.localStorage.setItem("reachZeroOn", reachZeroOn);
}

$('#defaultCountdown').countdown({
    until: reachZeroOn,
    compact: true, 
    onExpiry: end,
});

function end() { 
    alert('We have lift off!'); 
}

Working example: jsFiddle

Comments