gpt4 book ai didi

javascript - 时间戳倒计时变为负数

转载 作者:行者123 更新时间:2023-12-03 04:51:54 29 4
gpt4 key购买 nike

我有一个倒计时时间戳的脚本。它工作正常,但问题是它一直小于 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>

Output looks like 1 Days, 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);

关于javascript - 时间戳倒计时变为负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42620913/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com