Sunday, January 24, 2016

Set Timer on Cookie

$(function(){
    startTimer();
});
function startTimer()
{
    document.cookie = 'timer='+60; //Cookie
    if(document.cookie.replace(/(?:(?:^|.*;\s*)timer\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "") //The way to read cookie in javascript
    {
        var duration = document.cookie.replace(/(?:(?:^|.*;\s*)timer\s*\=\s*([^;]*).*$)|^.*$/, "$1");
        var timer = duration, minutes, seconds, hours;
         var t = setInterval(function ()
             {
             hours   = parseInt(timer /(60*60),10);
             minutes = parseInt((timer / 60) - (hours*60), 10);
             seconds = parseInt(timer % 60, 10);

             hours   = hours  < 10 ? "0" + hours : hours;
             minutes = minutes < 10 ? "0" + minutes : minutes;
             seconds = seconds < 10 ? "0" + seconds : seconds;

             $('.hours').html(hours);
             $('.minutes').html(minutes);
             $('.seconds').html(seconds);

             --timer;
             document.cookie = 'timer='+timer;

             if(timer < 0)
             {
                 clearInterval(t);
             }
             }, 1000);
    }
}

No comments:

Post a Comment