This is my code to display a countdown timer for otp, but it only displays static values and does not update every second as expected.
<?php // Set the target end time (in this example, 10 minutes from now) $endTime = time() + (10 * 60); // Calculate the remaining time $remainingTime = $endTime - time(); // Display the remaining time echo "<span id='countdown'></span>"; ?> <script> // Display the remaining time in minutes and seconds function displayCountdown() { var remainingTime = <?php echo $remainingTime; ?>; var minutes = Math.floor(remainingTime / 60); var seconds = remainingTime - (minutes * 60); document.getElementById("countdown").innerHTML = minutes + "m " + seconds + "s"; remainingTime--; if (remainingTime < 0) { clearInterval(interval); document.getElementById("countdown").innerHTML = "Time's up!"; } } var interval = setInterval(displayCountdown, 1000); </script>
Please point out what I'm missing.
Remember that PHP code is executed on the server - and does not affect JS ("browser time") execution. Your JS function actually looks like this:
Here, the problem is immediately visible: you are only decrementing the
remainingTime
during a single run of thedisplayCountdown
function. On the next call, the value is 600 again - because theremainingTime
variable is local.Therefore, the most straightforward solution is to move the variable outside the
displayCountdown
scope, like this: