首页 > 解决方案 > 为什么 setInterval 在使用 Date 方法时返回相同的值

问题描述

我正在尝试从中获取本地秒数,getSeconds但是当我console.log通过在秒数中添加函数的结果setInterval是相同的但它们正在增加时。请在下面找到我的代码;

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

标签: javascriptsetinterval

解决方案


您正在为间隔函数之外的时间(并且只有一次)分配值,因此它总是相同的。尝试:

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


推荐阅读