Countdown timer with cookie

Hi there,

I have a js countdown timer which counts down from 60 seconds to zero and when it hits zero it redirects the page.

Only problem is that when the user refreshes the page the timer obviously reverts to 60 seconds.

Does anyone have any code which would turn this into a cookie so that the location of the timer is stored each time the page is refreshed and then the timer continues from where it left off?

My timer is using setTimeout.

I’ve seen a couple of examples of this on various forums but none actually seem to work - my cookies are switched on.

Also, I cannot use form, input or anything else like this due to the third party software we’re using (long story!).

Any help would be lovely.

Thanks!

Presuming your countdown timer is running as a setInterval or setTimeout call every second, you could simply declare a variable with an inital value, i.e - 60 and then decrement it by 1 every time the function is called. :cool:

Then you would need to create a function to respond to the window.onunload event which then stores the value into the cookie…

Here’s an example:


var secondRemaining = 60;
var theFinalCountdown = setInterval("myFunc", 1000);

function myFunc() {
  //your countdown function
  secondsRemaining = secondsRemaining - 1;
}

function recordCookie() {
  //store secondsRemaining variable within cookie here
}

If you need any further help just let us know!