Rohhit
Rohhit

Reputation: 742

Restarting a timer from where it was when the user left the page

I have developed a JSP page. On this page, I have a count-down timer that displays time in hh:mm:ss. A link is provided to the previous page (page 2) from this page. After some work on page 2, control will be transferred to page 1 again.

I have a timer that starts when page 1 loads. When I go to page 2 and return to page 1, the timer gets refreshed. How can I make it start from where it was when I left the page?

Here's my timer code:

<script language="JavaScript">
function countdown( elementName, minutes, seconds )
{
    var element, endTime, hours, mins, msLeft, time;

    function twoDigits( n ) {
        return (n <= 9 ? "0" + n : n);
    }

    function getCurrentTime() {
         time = new Date();
         hours = time.getUTCHours();
         mins = time.getUTCMinutes();
         secs = time.getUTCSeconds();
         alert(hours + " " + mins + " " + secs);
    }

    function updateTimer() {
        msLeft = endTime - (+new Date);

        if ( msLeft < 999 ) {
            alert("please save your work and send your file!");
        } else {
            time = new Date( msLeft );
            hours = time.getUTCHours();
            mins = time.getUTCMinutes();
            secs = time.getUTCSeconds();
            element.innerHTML = (hours ? hours + ':' + twoDigits( mins ) : mins) + ':' + twoDigits(secs);
            setTimeout( updateTimer, time.getUTCMilliseconds() + 500 );
        }
        if( hours == 0 && mins == 0 && secs == 59 ) alert("dsdsdsdsdsd");
    }

    function setCookie(name, value, expires) {
        document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
    }

    function getCookie ( name ) {
        var cname = name + "=";               
        var dc = document.cookie;

        if ( dc.length > 0 ) {              
            begin = dc.indexOf(cname);       
            if (begin != -1) {           
                begin += cname.length;       
                end = dc.indexOf(";", begin);
                if (end == -1) end = dc.length;
                return unescape(dc.substring(begin, end));
            } 
        }
        return null;
    }
    var exp = new Date();                                  
    exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
    element = document.getElementById( elementName );
    endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
    updateTimer();
}
</script>

Upvotes: 0

Views: 1645

Answers (1)

Ha Nguyen
Ha Nguyen

Reputation: 926

I think you can use cookies to store the current time and one flag=true before you switch to page 2; when you come back to page 1 you de-active flag=false to continue to calculate the time.

you can do follow steps below:

1) create a js file with content:

function setCookie(key, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }

    document.cookie = key + "=" + value + expires + "; path=/";
}

function getCookie(key) {
    var nameEQ = key + "=";
    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, c.length);
        if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function removeCookie(key) {
    setCookie(key, "", -1);
}

2) At form 1 before click to go to form 2, you can set the current time to cookie.

setCookie("tracking_time", time_string, 5);

Please refer Javascript Date Time functions to know how to get/set a time string

3) when come back to form 1 from form 2, you can get time value from cookie , then you set to timer to continue count time.

var time_string = getCookie("tracking_time");

Then you parse time_string to object


This is a sample complete code

<html>
<head>
</head>
<body>
   <span id="countdown">Start</span>
   <script>
      function setCookie(key, value, days) {
         var expires = "";
         if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
         }

         document.cookie = key + "=" + value + expires + "; path=/";
      }

      function getCookie(key) {
         var nameEQ = key + "=";
         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, c.length);
            if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length, c.length);
         }
      return null;
   }

   function removeCookie(key) {
      setCookie(key, "", -1);
   }
   var countdown = document.getElementById("countdown");
   var days, hours, minutes, seconds;
   var target_date = getCookie("tracking_time");

   if (target_date == null) {
      target_date = new Date().getTime() + (2*60*60*1000); // set countdown 2 hours
   }

   function updateTimer() {
      setInterval(function () {
      // this line below will set to function that user click on link to go to form 2 
      setCookie("tracking_time", target_date, 1);
      // End line

      // find the amount of "seconds" between now and target
      var current_date = new Date().getTime();
      var seconds_left = (target_date - current_date) / 1000;

      // do some time calculations
      days = parseInt(seconds_left / 86400);
      seconds_left = seconds_left % 86400;

      hours = parseInt(seconds_left / 3600);
      seconds_left = seconds_left % 3600;

      minutes = parseInt(seconds_left / 60);
      seconds = parseInt(seconds_left % 60);

      // format countdown string + set tag value
      countdown.innerHTML = hours + "h: " + minutes + "m: " + seconds + "s";  

   }, 1000);
}

updateTimer();

</script>
</body>
</html>

Upvotes: 1

Related Questions