我有一个倒数时间戳的脚本。它运行良好,但问题的持续时间少于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:30
问题是,如果它小于零,则仍然为负。像 -3天,-3:-5:-5
如何停在0。
谢谢。
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);
if(timestamp <= 0)
{
clearInterval(timer);
}