This is my code to display a countdown timer for a otp, but its displaying only static value and is not getting updated every second like 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 am I missing.
3
Answers
May be you need to move the remaining time calculation from displayCountdown func. And the remaining time will be updated by the setInterval() method (every second). I hope this helps for you.
Remember, PHP code is executed on server – and won’t be able to affect JS ("browser-time") execution. Your JS function, effectively, looks like this:
Here, the problem is immediately visible: you only decrement
remainingTime
during a single run ofdisplayCountdown
function. The next time it’s called, the value is again 600 – asremainingTime
variable is local.Therefore, the most straightforward solution is to move that variable outside of
displayCountdown
scope, like this:You are defining remaining time in the function, so it will be 10 minutes every time the function is called.
You need to move the
var remainingTime = <?php echo $remainingTime; ?>;
to above the function. Like this:
Then it won’t get overwritten every time the interval calls the function