Reputation: 143
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!!
Upvotes: 0
Views: 490
Reputation: 350760
Indeed, a page's JavaScript does not run if you close your browser, or navigate away from it.
So if you are storing the number of seconds that is remaining in localStorage, then when you come back that number will not have changed, giving the behaviour you notice.
Instead of storing the remaining number of seconds, you should store the absolute time to which the counter is counting down. This value does not change during the counting down, so there will be no issue if you leave the page and come back to it. Nor do you have to update localStorage at every tick.
Here is the code:
// read previous deadline (unix time) or default to
// current time + 1 hour:
var deadline = +window.localStorage.getItem("detik")
|| new Date().getTime() + 3600*1000;
// save this time:
window.localStorage.setItem("detik", deadline);
if (deadline < new Date().getTime()) {
// In case during the user's absence the timer already expired:
end();
} else {
$('#defaultCountdown').countdown({
until: new Date(deadline),
compact: true,
onExpiry: end,
});
}
Make sure to first delete the localStorage entry you might already have.
Upvotes: 0
Reputation: 11836
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
Upvotes: 1