views:

545

answers:

1

I want to set a cookie with javascript. Easy enough. Lets say I set it for 15 minutes.

How would I make a count down timer show to show when the cookie expires? And even if they left the page I would want it to keep counting and when they come back to the page it would still have been counting down.

Sorry for the poor explanation. But I'm fairly sure its possile.

Thanks

+3  A: 

Store the time stamp of now + 15 minutes within a cookie if there is no cookie. Write a simple script that checks the difference between now and the timestamp every second.

Edit: sample code

// 200 seconds countdown
var countdown = 200; 

//current timestamp
var now   = Date.parse(new Date());

//ready should be stored in your cookie
var ready = Date.parse(new Date (now + countdown  * 1000)); // * 1000 to get ms


//every 1000 ms
setInterval(function()
{
    var sec = ( ready - Date.parse(new Date()) )/1000;
    document.title = sec + " seconds left";

},1000);
Ghommey
And just to add - Use setInterval() and NOT setTimeout() for timers. Really simplifies code IMO
Daniel S
Example perhaps?
Ben Shelock
I added a really short sample code. Let me know if it works.
Ghommey