javascript - 倒数计时器不刷新
问题描述
我的网站上有一个倒计时计时器,它以秒为单位倒计时(不需要分钟、小时、天等)
当将日期添加到变量中时,计时器可以正常工作并按我想要的方式显示,我遇到的唯一问题是它setInterval()
没有像预期的那样每秒刷新一次。var now = Date().getTime();
如果我从时间高于 2 小时的情况下删除 php 值,它会将计时器减半但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>
解决方案
我已经重写了您的代码,以使用更明显和更详细的变量名称将 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>
推荐阅读
- reactjs - 反应路由器不会在路由更改时渲染组件
- angular - 如何在 msal-angular 配置中使用 forceRefresh: true?
- pandas - 如何将值插入另一个表的列中?
- elasticsearch - 什么是常量分数
- angular - 如何将 asp.net core(后端)和 angular 8(前端)应用程序一起部署到 Google App Engine?
- android - 由于错误,无法更新 Firestore 中的数组
- java - 未定义的函数:'ST_GeomFromText' 使用 Spark / Java
- html - 如何像不完整的表格一样对齐 div?
- mysql - 无法在 Laravel 中与谷歌云应用引擎连接的 MySQL 上上传图片
- linux - 我无法在 fedora 32 上安装 crunch