首页 > 解决方案 > 倒数计时器不刷新

问题描述

我的网站上有一个倒计时计时器,它以秒为单位倒计时(不需要分钟、小时、天等)

当将日期添加到变量中时,计时器可以正常工作并按我想要的方式显示,我遇到的唯一问题是它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>

标签: javascript

解决方案


我已经重写了您的代码,以使用更明显和更详细的变量名称将 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>


推荐阅读