這是我的程式碼,用於顯示 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>
請指出我缺少什麼。
請記住,PHP 程式碼在伺服器上執行 - 並且不會影響 JS(「瀏覽器時間」)執行。您的 JS 函數實際上如下所示:
在這裡,問題立即可見:您僅在單次執行
displayCountdown函數期間遞減remainingTime。下次呼叫時,該值再次為 600 - 因為remainingTime變數是本地的。因此,最直接的解決方案是將該變數移到
displayCountdown範圍之外,如下所示: