使用JavaScript将倒计时器存储到cookie中,而不会在页面刷新或关闭后重新启动计时器

时间:2017-09-18 15:01:54

标签: javascript html cookies

我正在开发一个考试Web应用程序,我正在使用JavaScript来执行倒计时并将时间存储到cookie中,以便在页面刷新或有意关闭时,它不会从头开始倒计时一遍又一遍。

我的观察是它存储了cookie并从最后一个时间开始检索它,然后立即从头开始。

我的JavaScript代码

<script>
var  loginUser = "<?php echo $uid ?>";
// Defining the set Cookie method
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// Defining get cookie function
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 "";
}

// Return or Get the time stored in the cookie if available
   var oldTime = parseInt(getCookie(loginUser), 10);

// Set the date we're counting down to
var countDownDate = new Date().getTime() + ((4/180)*60*60*1000);

// Update the count down every 1 second
var x = setInterval(function() {

     // Get todays date and time
    var now = new Date().getTime();
    //
    var distance = countDownDate - now;
    var oldTime = parseInt(getCookie(loginUser), 10);
        setCookie(loginUser, distance, 30);

     if( isNaN(oldTime))
     {
         alert("new user NaN");
      // Find the distance between now an the count down date

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);
     }
     else{


        // Time calculations for days, hours, minutes and seconds from the saved distance
        // in the cookie
        var days = Math.floor(oldTime / (1000 * 60 * 60 * 24));
        var hours = Math.floor((oldTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((oldTime % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((oldTime % (1000 * 60)) / 1000);
     }





    //Output the result in an element with id="timer"
  document.getElementById("timer").value = hours + "h " + minutes + "m " + seconds + "s ";
    //var n = oldTime.toString();
    //document.getElementById("timer").value = n;


    // If the count down remains 15 minutes, write some text

if (minutes == 1 && seconds == 1) {
        alert("Hello! 1 minute gone");
    }


    // If the count down is over, write some text
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("timer");
        timer.value= "EXPIRED";
        alert("Hello! Exam is over");
        location = "http://localhost:81/aquaexam/exam_complete.php?id=1";
    }
}, 1000);
</script>

我的HTML代码

<tr width="100%" style="text-align:right; align:right;"> <td >  <input type="text" name="timer" id="timer" size="20" readonly="true" style="text-align:center;"/></td></tr>

1 个答案:

答案 0 :(得分:0)

我终于解决了它。

最终JavaScript代码。 您只需复制并粘贴即可使用。

<script>
// define variable for cookie name using the user login id
var  loginUser = "<?php echo $uid ?>";
// Defining the set Cookie method
function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// Defining get cookie function
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 "";
}

// Function that will call when document loaded.
window.onload = function () {
// Return or Get the time stored in the cookie if available
   var oldTime = parseInt(getCookie(loginUser), 10);

   if(isNaN(oldTime) == false)
    {
            // Reset the date or time we're counting down to by
          //adding the Cookie time to the present for continous countdown
          var countDownDate = new Date().getTime() + oldTime;

         // Update the count down every 1 second    
        var x = setInterval(function() {
        // Get todays date and time
        var now = new Date().getTime();
            // Find the distance between now an the count down date
        var distance = countDownDate - now;
        setCookie(loginUser, distance, 30);
        // Update the count down every 1 second

        // Time calculations for days, hours, minutes and seconds from the saved distance
        // in the cookie
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);


         //Output the result in an element with id="timer"
  document.getElementById("timer").value = hours + "h " + minutes + "m " + seconds + "s ";

            // If the count down remains 15 minutes,  notification alert
    if (minutes == 15 && seconds == 1) {
        alert("Hello! 15 minutes to go" );
    }

    // If the count down remains 5 minutes,  notification alert
    if (minutes == 5 && seconds == 1) {
        alert("Hello! 5 minutes to go" );
    }

// If the count down is over, notification alert and automatically submits the exam
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("timer");
        timer.value= "EXPIRED";
        alert("Hello! Exam is over");
        location = "http://localhost:81/aquaexam/exam_complete.php?id=1";
    }

        }, 1000);
     }
     else{

     // Set the date or time we're counting down to
    var countDownDate = new Date().getTime() + ((1)*60*60*1000);

           // Update the count down every 1 second
               var x = setInterval(function() {
             // Get todays date and time
               var now = new Date().getTime();
           // Find the distance between now an the count down date
               var distance = countDownDate - now;

               setCookie(loginUser, distance, 30);


      // Find the distance between now an the count down date

        // Time calculations for days, hours, minutes and seconds
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    //Output the result in an element with id="timer"
  document.getElementById("timer").value = hours + "h " + minutes + "m " + seconds + "s ";


        // If the count down remains 15 minutes,  notification alert
    if (minutes == 15 && seconds == 1) {
        alert("Hello! 15 minutes to go" );
    }

    // If the count down remains 5 minutes,  notification alert
    if (minutes == 5 && seconds == 1) {
        alert("Hello! 5 minutes to go" );
    }

// If the count down is over, notification alert and automatically submits the exam
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("timer");
        timer.value= "EXPIRED";
        alert("Hello! Exam is over");
        location = "http://localhost:81/aquaexam/exam_complete.php?id=1";
    }
}, 1000);
   }
}

我的HTML代码

<tr width="100%" style="text-align:right; align:right;"> <td >  <input type="text" name="timer" id="timer" size="20" readonly="true" style="text-align:center;"/></td></tr>