search

Home  >  Q&A  >  body text

JavaScript timer does not update every second

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.

P粉340980243P粉340980243229 days ago482

reply all(1)I'll reply

  • P粉376738875

    P粉3767388752024-04-03 00:59:16

    Remember that PHP code is executed on the server - and does not affect JS ("browser time") execution. Your JS function actually looks like this:

    sssccc

    Here, the problem is immediately visible: you are only decrementing the remainingTime during a single run of the displayCountdown function. On the next call, the value is 600 again - because the remainingTime variable is local.

    Therefore, the most straightforward solution is to move the variable outside the displayCountdown scope, like this:

    sssccc

    reply
    0
  • Cancelreply