2017-03-06 109 views
0

我有一個倒計時時間戳的腳本。它工作正常,但它保持不足0的問題變爲否定。我希望它停止在零。時間戳倒計時進入負面

// $nowtime is a date in future 
 
var startLive = new Date("<?php echo $nowtime; ?>"); 
 
var timestamp = startLive - Date.now(); 
 

 
timestamp /= 1000; // from ms to seconds 
 

 
function component(x, v) { 
 
    return Math.floor(x/v); 
 
} 
 

 
var $div = $('.time'); 
 

 
timer = setInterval(function() { 
 

 
    timestamp--; 
 

 
    var days = component(timestamp, 24 * 60 * 60), 
 
    hours = component(timestamp, 60 * 60) % 24, 
 
    minutes = component(timestamp, 60) % 60, 
 
    seconds = component(timestamp, 1) % 60; 
 

 
    $div.html(days + " days, " + hours + ":" + minutes + ":" + seconds); 
 

 

 
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

輸出看起來像1天,6時10分三十〇秒

問題是,如果它是小於0,卻還在繼續爲負。像-3天,-3:-5:-5

如何停止在0

感謝。

回答

1
timer = setInterval(function() { 

    /* if timestamp <= 0 return means skip rest of function */ 
    if(timestamp <= 0) { 
     clearInterval(timer); 
     return; 
    } 

    timestamp--; 

    var days = component(timestamp, 24 * 60 * 60), 
     hours = component(timestamp,  60 * 60) % 24, 
     minutes = component(timestamp,   60) % 60, 
     seconds = component(timestamp,   1) % 60; 

    $div.html(days + " days, " + hours + ":" + minutes + ":" + seconds); 


}, 1000); 
+0

謝謝。加工。我嘗試了我自己,但忘了返回:) – Phoenix

+0

@Phoenix歡迎您!請不要忘記標記爲已接受 – caramba

+0

實際上,您應該使用clearInterval(timer)清除間隔。 '而不是隻返回,否則間隔仍然會在後臺調用。 如果您在if語句內和返回之前添加一個'console.log('something')',您將看到間隔仍在被調用。 –

0
if(timestamp <= 0) 
{ 
clearInterval(timer); 
} 
+0

儘管這段代碼可能會解決這個問題,但[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要用解釋性註釋來擠佔代碼,這會降低代碼和解釋的可讀性! – kayess