首页  >  问答  >  正文

JavaScript 计时器不会每秒更新

这是我的代码,用于显示 otp 的倒计时器,但它仅显示静态值,并且不会像预期那样每秒更新。

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

请指出我缺少什么。

P粉340980243P粉340980243180 天前369

全部回复(1)我来回复

  • P粉376738875

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

    请记住,PHP 代码在服务器上执行 - 并且不会影响 JS(“浏览器时间”)执行。您的 JS 函数实际上如下所示:

    sssccc

    在这里,问题立即可见:您仅在单次运行 displayCountdown 函数期间递减 remainingTime 。下次调用时,该值再次为 600 - 因为 remainingTime 变量是本地的。

    因此,最直接的解决方案是将该变量移到 displayCountdown 范围之外,如下所示:

    sssccc

    回复
    0
  • 取消回复