我有一个倒计时时间戳的脚本。它工作正常,但它继续低于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);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
&#13;
输出看起来像1天,6:10:30
问题是如果它小于零,它仍然是负数。类似 -3天,-3:-5:-5
如何停在0.
感谢。
答案 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);
答案 1 :(得分:0)
if(timestamp <= 0)
{
clearInterval(timer);
}