JavaScript timer does not update every second
P粉340980243
P粉340980243 2024-04-02 19:04:44
0
1
360

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粉340980243
P粉340980243

reply all(1)
P粉376738875

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!