Javascript -最好的两种方法来创建一个简单的时钟

Javascript - best of 2 ways to create a simple clock

本文关键字:一个 时钟 简单 两种 Javascript 方法 创建      更新时间:2023-09-26

所以我正在为我的网站创建一个时钟,我已经想到了两种方法…

1)

var today = new Date();
this.start = function() {
    this.update();
    setInterval(this.update,1000);
}
this.update = function() {
    today.setSeconds(today.getSeconds() + 1);
}

2)

var today = new Date();
this.start = function() {
    this.update();
    setInterval(this.update,1000);
}
this.update = function() {
    today = new Date();
}

哪个更好?每秒生成一个新的日期还是只是更新?(或者第三种方法)

对于每个循环使用new Date()要好得多,因为setInterval上使用的间隔不会100%恒定。

new Date()将是准确的,无论setInterval的方差


这是我几天前回答的一个片段。它解释了使用固定值递增(或递减)的setInterval的问题。

注意不要创建使用固定值递增的计时器

在你的代码中,有

setTimeout(() => this.count--, 1000);

目的是让您每秒减少一次count属性,但这不是您将保证的行为。

看看这个小脚本

var state = {now: Date.now()};
function delta(now) {
  let delta = now - state.now;
  state.now = now;
  return delta;
}
setInterval(() => console.log(delta(Date.now())), 1000);
// Output
1002
1000
1004
1002
1002
1001
1002
1000

我们使用setInterval(fn, 1000),但实际间隔每次变化几毫秒。

如果你把浏览器的焦点切换到另一个标签,打开一个新标签等,问题就会被夸大。看看这些零星的数字

1005 // close to 1000 ms
1005 // ...
1004 // a little variance here
1004 // ...
1834 // switched focus to previous browser tab
1231 // let timer tab run in background for a couple seconds
1082 // ...
1330 // ...
1240 // ...
2014 // switched back to timer tab
1044 // switched to previous tab
2461 // rapidly switched to many tabs below
1998 // ...
2000 // look at these numbers...
1992 // not even close to the 1000 ms that we set for the interval
2021 // ...
1989 // switched back to this tab
1040 // ...
1003 // numbers appear to stabilize while this tab is in focus
1004 // ...
1005 // ...

因此,这意味着您不能依赖每1000毫秒运行一次setTimeout(或setInterval)函数。count将根据各种各样的因素以很大的方差递减。

要解决这个问题,需要使用delta。这意味着在计时器的每个"滴答"之前,您需要使用Date.now获取时间戳。在下一个刻度处,获取一个新的时间戳,并从新的时间戳中减去之前的时间戳。这是你的delta。使用此值,将其添加到计时器的总ms中,以获得计时器已运行的精确的毫秒数。