簡體   English   中英

setTimeout() 運行函數但日期未更新

[英]setTimeout() runs function but date is not updated

我在有關 setTimeout() 的所有其他線程中找不到任何修復,所以這里是:

我做了一個數字時鍾,如果你刷新頁面,它會顯示正確的時間。 但是 setTimeout 不會每 500 毫秒刷新一次頁面? 老師看了我的代碼,竟然不知道為什么? 所有變量都在更新功能中更新,並且時鍾在不運行的情況下工作。 所以我知道唯一的錯誤是我調用 setTimeout 函數的地方。

 const weekDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; let date = new Date(); function formatNumber(number) { return number < 10 ? "0" + number : number; } function renew() { for (let i = 0; i < weekDays.length; i++) { if (date.getDay() === i) { document.getElementById("day").innerText = weekDays[i]; } } document.getElementById("hours").innerText = formatNumber(date.getHours()); document.getElementById("mins").innerText = formatNumber(date.getMinutes()); document.getElementById("secs").innerText = formatNumber(date.getSeconds()); if (date.getHours() > 0 && date.getHours() < 12) { document.getElementById("period").innerText = "AM"; } else { document.getElementById("period").innerText = "PM"; } window.setTimeout(renew, 500); } renew();
 <html lang="en"> <head> <meta charset="UTF-8"> <title>Digital Clock</title> <link rel="stylesheet" href="style.css"> </head> <body> <div id="clock"> <!-- Time units wrapper --> <span class="wrap-time"> <!-- Time unit - Day --> <span class="time-unit"> <span id=day class="large day">Mon</span> <span class="small">DAY</span> </span> <!-- Time unit - Hours --> <span class="time-unit"> <span id=hours class="large hours">00</span> <span class="small">HOURS</span> </span> <span class="separator">:</span> <!-- Time unit - Minutes --> <span class="time-unit"> <span id=mins class="large minutes">00</span> <span class="small">MINUTES</span> </span> <span class="separator">:</span> <!-- Time unit - Seconds --> <span class="time-unit"> <span id="secs" class="large seconds">00</span> <span class="small">SECONDS</span> </span> <!-- Time unit - Period --> <span class="time-unit"> <span id=period class="large period">AM</span> <span class="small">PERIOD</span> </span> </span> </div> </body> </html>

您的更新功能應首先更新日期,然后進一步使用它。

function renew() {
   date=new Date();
   for (let i = 0; i < weekDays.length; i++) {
     if (date.getDay() === i) {
       document.getElementById("day").innerText = weekDays[i];
    }
   }

  document.getElementById("hours").innerText = formatNumber(date.getHours());
  document.getElementById("mins").innerText = formatNumber(date.getMinutes());
  document.getElementById("secs").innerText = formatNumber(date.getSeconds());

  if (date.getHours() > 0 && date.getHours() < 12) {
    document.getElementById("period").innerText = "AM";
  } else {
    document.getElementById("period").innerText = "PM";
  }
  window.setTimeout(renew, 500);
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM