Countdown timer with cookies

Discussion in 'JavaScript' started by smuel, May 25, 2010.

  1. #1
    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!
     
    smuel, May 25, 2010 IP
  2. ccoonen

    ccoonen Well-Known Member

    Messages:
    1,606
    Likes Received:
    71
    Best Answers:
    0
    Trophy Points:
    160
    #2
    on leaving the page: document.cookie = 'expirationdate=[how many seconds are left]; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'

    then just read the cookie, next time, or keep recreating the cookie.
     
    ccoonen, May 25, 2010 IP
  3. aeroz1

    aeroz1 Active Member

    Messages:
    492
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #3
    On load instead of starting your timer @ 60 seconds, set a variable to 60 and then use that variable. What that will let you do is intercept the variable before starting the timer.
    now before you start the timer you run a check for a cookie and if there, pull its time, set the variable from earlier to that new time and then start your countdown.
    The hard part will be setting the cookie. there are lots of cookie plug-ins out there (may save you some time). depending on what script you are using for counting down there will be a loop of some kind (depending). You need to put in your cookie "counter" into that loop. as the seconds count down your cookie recording function sets/updates the users cookie. You have to be careful here, (again depending) your loop may cycle @ a very rapid pace, so fast that if you set a cookie every time you loop it will cause problems for the user (performance of setting a cookie every 0.xx seconds).
    So in your cookie setting function you need to record the last time it ran and only have it run again if X number of second have past.
     
    aeroz1, Jun 7, 2010 IP