GANIZ
GANIZ

Reputation: 105

Countdown clock not reset on refresh

I have a countdown clock here that resets when the page is refreshed. I would appreciate it if someone could help me?

I have included the script below.

<script type="text/javascript">
    var ticker = function() {
        $("#ticker").css({
            left: "120%"
        }).animate({
            left: "-420px"
        }, 6000, 'linear', ticker);
    }

    ticker();
</script>

Upvotes: 2

Views: 438

Answers (1)

Mayday
Mayday

Reputation: 5146

Considering you need it to be "running" while user is not in the page, I will point out that Javascript is a client side scripting language Javascript code is run in local side i.e its interpereted by the browser. This makes hard to "keep" track of things if the user refreshes the page until unless you have have stored them somewhere. There can be different approaches for your solution such as:-

  1. LocalStorage
  2. Cookies
  3. Server Side Clock

You can use either of the three. You can use localstorage to save the clock end time and whenever the user refreshes the page get the value from localstorage and start you clock accordingly. Similar approach can be used with cookies. Or you can use some server side code to initialize the clock whenever your page loads the server will set start the clock accordingly. but there can be some lag as mentioned above in comments. So the best approach in my opinion, if you just want to use javascript, would be to use cookies/localstorage to save the exact time when the countdown will reach value 0. So everytime you load into the page, you can get the stored value , and get how long is missing yet and set the clock accordingly.

Some coding

Create a cookie with expiration time:

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+d.toUTCString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

Get a cookie:

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

Sample of use:

function checkCookie() {
  var clock = getCookie("clock");
  if (clock != "") {
    //You already have the cookie. Make use of it
  } else {
    //You still dont have the cookie, create new clock, and save cookie
    //i.e.
    setCookie("clock", new Date().getTime().toString(), 365);
  }
}

Upvotes: 1

Related Questions