简体   繁体   中英

Countdown Timer not refreshing

I have a countdown timer on my website and it counts down in seconds (don't want minutes, hours, days, etc.)

The timer works and shows up as I want it to when the date is added into the variable, the only issue I'm having is that setInterval() is not refreshing it every second like it is supposed to. If I remove the php value from var now = Date().getTime(); if the time is higher than 2 hours, it cuts the timer in half but setInterval() refreshes it so I'm at a loss lol

Here is my code:

 <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, YH:i:s', $new); $dateNow=Date('M d, YH:i:s'); ?> <p id="timer"></p> 

I've rewritten your code to place the php variables at the top using more obvious and verbose variable names. I may have messed up the algorithm but hopefully this helps.

 /* <?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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM