簡體   English   中英

為什么setInterval在使用Date方法時返回相同的值

[英]Why does setInterval return the same value when using the Date method

我試圖從getSeconds獲取本地秒數,但是當我通過在setInterval添加函數來console.log結果時,秒數相同但它們正在增加。 請在下面找到我的代碼;

const time = new Date();
function clock() {
   const seconds = time.getSeconds();
   console.log(seconds)
}
let interval = setInterval('clock()', 1000);

您正在為間隔函數之外的時間(並且只有一次)分配時間值,因此它總是相同的。 嘗試:

 function clock() { let time = new Date(); const seconds = time.getSeconds(); console.log(seconds) } let interval = setInterval('clock()', 1000);

你創建了一個數據對象(在某個時刻),然后你在同一個數據對象上調用 getSeconds 所以你有相同的結果

 function clock() { const seconds = new Date().getSeconds(); console.log(seconds) } let interval = setInterval(clock, 1000);

暫無
暫無

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

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