繁体   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