Showing posts with label How to make counter not reset on page refresh javascript. Show all posts
Showing posts with label How to make counter not reset on page refresh javascript. Show all posts

Saturday, 4 November 2017

How to make timer that not reset when page refresh javascript

<form name="counter">
    <input type="text" size="8" name="jimmy" id="counter">
</form>

<script type="text/javascript">
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.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 "";
}

var cnt = 60;
function counter(){
    if(getCookie("cnt") > 0){
  cnt = getCookie("cnt");
 }
 cnt -= 1;
 document.cookie = "cnt="+ cnt;
 jQuery("#counter").val(getCookie("cnt"));

 if(cnt>0){
  setTimeout(counter,1000);
 }

}

counter();
</script>