0

I am trying to make a count down timer. I manage to make one but the problem with this is it stops when I close browser. So when user revisit my site it restart again. What I want is to keep that timer. For example, if user leaves my site at timer 22:14:09. So timer will continue. Lets say the user revisits my site after an hour so the time should be 21:14:09. How can I do that?

Here is my JS

$(function () {
var hrs, mins, secs, TimerRunning, TimerID,
    Timer = {
        init: function () {
            hrs          = 23;
            mins         = 59;
            secs         = 59;
            TimerRunning = false;
            Timer.StopTimer();
            Timer.StartTimer();
         },

         StopTimer: function () {
            if(TimerRunning)
               clearTimeout(TimerID);
            TimerRunning=false;
         },

         StartTimer: function () {
            TimerRunning = true;
            $('.timer').html(Timer.Pad(hrs) + ":" + Timer.Pad(mins) + ":" + Timer.Pad(secs));
            TimerID = self.setInterval("StartTimer()", 1000);

            if(hrs == 0 && mins == 0 && secs == 0)
               StopTimer();

            if (secs == 0) {
               mins--;
               secs = 59;
            }
            if (mins == 0) {
                hrs--;
                mins = 59;
            }
            secs--;
            setTimeout(function () { Timer.StartTimer(); }, 1000);
         },

         Pad: function (number) {
            if(number < 10)
               number = 0+""+number;
            return number;
         }

    };

Timer.init();
});

Update

DEMO

4
  • Move the timer to the server side. Commented Oct 31, 2012 at 7:54
  • Could you elaborate your answer a bit? Commented Oct 31, 2012 at 7:55
  • 1
    No need any serverside here. Just set the cookie on page unload. Commented Oct 31, 2012 at 7:57
  • Please see my updates post which is in italic. Sorry for the confusion. Commented Oct 31, 2012 at 8:04

3 Answers 3

1

Here is my solution for this problem.

// use hours, minutes & seconds to set time limit
var hours = 1, 
    minutes = 30, 
    seconds = 0,
    maxTime =  ( ( hours * 3600 ) + ( minutes * 60 ) + seconds ) * 1000,
    // if timeleft not in localStorage then default to maxTime
    timeLeft = ( localStorage.timeLeft || maxTime ),
    startTime = new Date(),
    intervalRef;

// check if user has already used up time
if( timeLeft > 0 ) {

    intervalRef = setInterval( setTimeLeft, 5000 );
} else {

    stopTrackingTime();
}

function setTimeLeft( ) {

    // if user has used up time exit
    if( localStorage.timeLeft < 0 ) {

        stopTrackingTime();
    }

    // calculate how long user has left
    var elapsed = ( new Date() - startTime );
    localStorage.timeLeft = timeLeft - elapsed;
};

// function called once user has used up time
function stopTrackingTime( ) {

    clearInterval( intervalRef );
    alert( "end of time allowed" );
}

Fiddle here

Sign up to request clarification or add additional context in comments.

Comments

0

You could store the time in LocalStorage, and it would be persistent across browser restarts.

In your case something as simple as

localStorage["mytimer"] = JSON.stringify([hrs, mins, secs]);

should work for storage, and you could do

var previousTime = JSON.parse(localStorage["mytimer"]);

to retrieve the previous value.

You could read more about it here: http://diveintohtml5.info/storage.html.

7 Comments

Please see my updated post which is in italic. That is what I want
@al0ne just store time spent on the site in local storage rather than the current time. localStorage["timeSpent"] = JSON.stringify( [hrsSpent, minsSpent, secsSpent])
@Bruno I added these two lines but still it does not work the way I wanted localStorage["mytimer"] = JSON.stringify([hrs, mins, secs]); var previousTime = JSON.parse(localStorage["mytimer"]); //$('.timer').html(Timer.Pad(hrs) + ":" + Timer.Pad(mins) + ":" + Timer.Pad(secs)); $('.timer').html(previousTime);
It still restarts from beginning.
Just be aware that using local storage (cookies, or html5 local storage) opens up your code to the possibility the timer data can be adjusted manually by the user. If you are coding an exam or something else that requires security around your timer, do not use local storage.
|
0

You could modify your StartTimer function so that every time it is called a local time stamp (new Date) be saved in cookie or localStorage. Besides, the setTimeout isn't very reliable, your should adjust the time count with real time every now and then.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.