2015-02-24 78 views
0

我需要幫助。 我正在爲我的遊戲網站製作一個倒計時腳本,該腳本抓取數據庫的結束時間並倒計時,直到當前時間等於數據庫時間。 但我似乎無法讓它停止,當它達到0. 我已經看着setTimeout(),我不明白我如何得到這個工作。停止jquery計時器,當它達到0

此外,當頁面刷新時,它會從數據庫時間再次啓動計時器。我怎麼會更新數據庫到剩下的時間或停止刷新計時器。

非常感謝。下面是劇本我到目前爲止

<?php 
include "header.php"; 

?> 
<html> 
<head> 
<script type="text/javascript"> 
var curTime = Math.floor((new Date()).getTime()/1000); // replaced with PHP time(), presumably 
var endTime = Math.floor((new Date()).getTime()/1000) + <?php echo $user_class->jail;?>; 

function tick() 
{ 
    var secs = endTime - cTime; 
    var mins = Math.floor(secs/60); 
    secs %= 60; 
    document.getElementById("ticker").innerHTML = 
     mins + " minutes, " + secs + " seconds"; 
    ++curTime; 
} 
</script> 
</head> 
<body onload="setInterval(tick,1000); tick();"> 
<h3>Time remaining is <span id="ticker"></span></h3> 

</body> 
</html> 

我的數據庫通過cron目前更新每隔1分鐘,因此能進能出,由於cron的。但我想知道是否有辦法通過倒數來更新數據庫,所以它會像其他定時器一樣精確。

+0

clearInterval()? – Robert 2015-02-24 16:01:22

回答

1

如果()在你的週期結束將這個()函數

if(endTime < curTime) clearInterval(i); 

和將您的onload值更改爲此。

<body onload="i = setInterval(tick,100); tick();"> 

clearInterval應該可以工作。 要當心這條線

var secs = endTime - cTime; 

這可能包含在您的ctime變種一個錯字

var secs = endTime - curTime; 
+0

謝謝,這已經得到了計時器停止時,它到達0,但我不得不改變 to ,因爲它快速倒計時秒數 – 2015-02-24 16:11:15

+0

哦,是的,我把它減少到100來測試我的小提琴。我忘了把它設回1000,抱歉:) – 2015-02-24 16:15:27

0

發現當你調用setInterval函數,它返回創建的計時器(它只是一個數字)的處理程序。你可以使用此處理停止計時器通過將其傳遞給clearInterval功能

例如:

timer = setTimeout(function() { console.log('hello'); }, 5000); 
... 
// This will stop timer 
clearInterval(timer); 
0

我重構你的代碼了一下,不應該過多的混合HTML/JS/CSS/PHP 。

文件:xxx.php:

<?php include "header.php"; ?> 
<html> 
<head> 
</head> 

<body> 
<h3>Time remaining is <span id="ticker"></span></h3> 
<input id="end_time" type="hidden" value="<?php echo $user_class->jail; ?>" /> 

<script src="scripts.js"></script> 
</body> 
</html> 

文件:scripts.js中

window.onload = function() { 
    var timer; 
    var curTime = Math.floor((new Date()).getTime()/1000); // replaced with PHP time(), presumably 
    var endTime = Math.floor((new Date()).getTime()/1000) + document.getElementById('end_time').value; 

    function tick() { 
     var secs = endTime - curTime; 
     var mins = Math.floor(secs/60); 
     secs %= 60; 
     document.getElementById("ticker").innerHTML = 
      mins + " minutes, " + secs + " seconds"; 
     ++curTime; 
     if (curTime > endTime) { 
      stopTimer(); 
     } 
    } 
    function startTimer() { 
     timer = setInterval(tick,1000); 
    }  
    function stopTimer() { 
     clearInterval(timer); 
    } 
    startTimer(); 
};