页面刷新倒计时器不会继续使用javascript

时间:2016-08-13 11:08:08

标签: javascript

<html>
<head>
<script>

var seconds=3600;
function secondPassed() {

   var minutes = Math.round((seconds-30)/60);
    console.log(minutes);
    var hours=Math.round((minutes)/60);

   var remainingSeconds = seconds % 60;
   if (remainingSeconds < 10) {
       remainingSeconds = "0" + remainingSeconds;  
    }

    document.getElementById('countdown').innerHTML =hours + ":"+ minutes + ":" + remainingSeconds;
    if (seconds == 0) {
        clearInterval(myVar);
        document.getElementById('countdown').innerHTML = "Time Out";
    } else {
        seconds--;
    }

}
var myVar = setInterval(secondPassed ,1000);

</script>

</head>
<body>
<p id="countdown"></p>
</body>
</html>

我的问题:页面刷新和倒数计时器不会继续。

1 个答案:

答案 0 :(得分:1)

您可以仅使用javascript Cookie执行此操作,但需要使用两个文件 第一个文件包含倒计时所需的总时间,即在您的代码中为3600秒

让我们先获取index.html编写代码的文件

&#13;
&#13;
cv::Point()
&#13;
&#13;
&#13;

接下来的第二个文件让我们把time.html添加到下面的代码

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
	<title>Countdown timer</title>
	<script type="text/javascript">
		var seconds = 3600;
		document.cookie = "timer=" + seconds;
		window.location.href = "time.html";
	</script>
</head>
<body>

</body>
</html>
&#13;
&#13;
&#13;

注意:每当你想运行倒数计时器时,只需运行time.html,即使你也刷新,时间仍然相同

注意:如果您想要刷新页面或想要在时间添加时添加您的活动

&#13;
&#13;
<html>
<head>
<script>


function getCookie(name) {
var nameEQ = name + "=";
//alert(document.cookie);
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);
if (c.indexOf(nameEQ) != -1) return c.substring(nameEQ.length,c.length);
}
return null;
} 


// var seconds=7200;
// document.cookie = "timer=" + seconds;
function secondPassed() {

  seconds = parseInt(getCookie('timer'));
  console.log(seconds);
   var minutes = parseInt(seconds / 60, 10);
    console.log(minutes);

   var  remainingSeconds = parseInt(seconds % 60, 10);

   if (remainingSeconds < 10) {
       remainingSeconds = "0" + remainingSeconds;  
    }

    document.getElementById('countdown').innerHTML =  minutes + ":" + remainingSeconds + ' minutes remaning';
    if (seconds == 0) {
        clearInterval(myVar);
        document.getElementById('countdown').innerHTML = "Time Out";
    } else {
        seconds--;
    }
    document.cookie = "timer=" + (seconds);

}
var myVar = setInterval(secondPassed ,1000);

</script>

</head>
<body>
<p id="countdown"></p>
</body>
</html>
&#13;
&#13;
&#13;