JavaScript Timer:使用会话开始时间不起作用

时间:2014-02-26 17:35:43

标签: javascript php html session session-cookies

我使用JavaScript Timer制作测验系统,该系统使用会话开始时间来计算计时器工作所需的时间。它在某些系统上工作正常但不是全部 有人可以帮帮我..?

var ct = setInterval("calculate_time()",100); // Start clock.
function calculate_time()
{
   var end_time = "<?php echo $_SESSION['start_time']; ?>"; // Get end time from session variable (total time in seconds).
   var dt = new Date(); // Create date object.
   var time_stamp = dt.getTime()/1000; // Get current minutes (converted to seconds).
   var total_time = end_time - Math.round(time_stamp); // Subtract current seconds from total seconds to get seconds remaining.
   var mins = Math.floor(total_time / 60); // Extract minutes from seconds remaining.
   var secs = total_time - (mins * 60); // Extract remainder seconds if any.

   if(secs < 10){secs = "0" + secs;} // Check if seconds are less than 10 and add a 0 in front.
   document.getElementById("txt").value = mins + ":" + secs; // Display remaining minutes and seconds.

  // Check for end of time, stop clock and display message.
  if(mins <= 0)
  {
     if(secs <= 0 || mins < 0)
     {
        clearInterval(ct);
        document.getElementById("txt").value = "0:00";
        var form = document.createElement("form");
        form.action = "http://www.example.org/q/conflinux/expire_me.php";
        form.method = "post"
        document.body.appendChild(form);
        form.submit();       
     }
   }
}

.....
.....

<form> <input id="txt" readonly> </input></form>

1 个答案:

答案 0 :(得分:1)

这对我有用 - 我将ct设置为全局变量并且只存储一次结束时间

请将setInterval("calculate_time()",100);更改为setInterval(calculate_time,100);

如果您不想污染全局范围,可以创建自己的命名空间

Live Demo

var ct, end_time = <?php echo $_SESSION['start_time']; ?>; // Get end time from session variable (total time in seconds). 

window.onload=function() { // make sure the output field exists
  ct = setInterval(calculate_time,100); // Start clock.
}
function calculate_time() {
  var dt = new Date(); // Create date object.
  var time_stamp = dt.getTime()/1000; // Get current minutes (converted to seconds).
  var total_time = end_time - Math.round(time_stamp); // Subtract current seconds from total seconds to get seconds remaining.
  var mins = Math.floor(total_time / 60); // Extract minutes from seconds remaining.
  var secs = total_time - (mins * 60); // Extract remainder seconds if any.
  if(secs < 10){secs = "0" + secs;} // Check if seconds are less than 10 and add a 0 in front.
  document.getElementById("txt").value = mins + ":" + secs; // Display remaining minutes and seconds.
// Check for end of time, stop clock and display message.
  if(mins <= 0) {
    if(secs <= 0 || mins < 0)  {
     clearInterval(ct);
     document.getElementById("txt").value = "0:00";
     var form = document.createElement("form");
     form.action = "http://www.example.org/q/conflinux/expire_me.php";
     form.method = "post"
     document.body.appendChild(form);
     form.submit();
   }
  }
 }