[英]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.