我的网站上有一个倒计时计时器,它以秒为单位倒计时(不需要分钟,小时,天等)
当将日期添加到变量中时,计时器会工作并按照我的期望显示,我唯一遇到的问题是setInterval()
并没有像预期的那样每秒刷新一次。如果我从var now = Date().getTime();
中删除php值(如果时间超过2小时),则会将计时器减半,但setInterval()
会刷新它,所以我很茫然
这是我的代码:
<script type="text/javascript">
var countDownDate = new Date("<?php echo $newDate; ?>").getTime();
var x = setInterval(function() {
var now = new Date("<?php echo $dateNow; ?>").getTime();
var distance = countDownDate - now;
var seconds = Math.floor((distance % (1000 * "<?php echo $time; ?>")) / 1000);
document.getElementById("timer").innerHTML = seconds + " s ";
console.log('tick');
if (distance < 0) {
clearInterval(x);
document.getElementById("timer").innerHTML = "Finished";
}
}, 1000);
</script>
<?php
$date="2018-11-16 15:32:16"; // This date comes from the database
$time="7200"; // Adds 7200 Seconds to date
$dateinsec=strtotime($date);
$new=$dateinsec+$time;
$newDate=date('M d, Y H:i:s', $new);
$dateNow=Date('M d, Y H:i:s');
?>
<p id="timer"></p>
答案 0 :(得分:0)
我已经重写了您的代码,以使用更明显且冗长的变量名称将php变量置于顶部。我可能弄错了算法,但希望能有所帮助。
/*
<?php
$date="2018-11-16 15:32:16"; // This date comes from the database
$countdown_date = strtotime( $date ); // convert that date to seconds
$added_time = "7200"; // Seconds we'll add to date
$countdown_date += $added_time; // countdown_date is now the date + added_time in seconds
$countdown_date *= 1000; // now countdown_date is in milliseconds
?>
const countDownDate = <?php echo $countdown_date; ?>;
*/
const countDownDate = 1542418336000;
const x = setInterval(function() {
const differenceInMillis = countDownDate - Date.now();
const differenceInSeconds = Math.floor( differenceInMillis / 1000 );
document.getElementById("timer").innerHTML = differenceInSeconds + "s";
if (differenceInMillis < 0) {
clearInterval(x);
document.getElementById("timer").innerHTML = "Finished";
}
}, 1000);
<p id="timer"></p>