![](/img/trans.png)
[英]why setInterval method does not work if value function in a var?
[英]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.