Javascript -最好的两种方法来创建一个简单的时钟
Javascript - best of 2 ways to create a simple clock
所以我正在为我的网站创建一个时钟,我已经想到了两种方法…
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
中,以获得计时器已运行的精确的毫秒数。
相关文章:
- 创建一个类似链接的按钮,并通过Javascript函数打开一个新的弹出窗口
- jQuery:循环一个具有不同超时值的循环
- 当包含另一个asp文件时,是否也包含所有引用的样式和脚本页面
- 从javascript创建一个列表
- 节点导出返回一个空对象
- 使用clickToggle并在单击另一个元素时关闭元素
- 我可以在json对象中添加一个函数吗
- 使用javascript将动态表从一个html页面打印到另一个html页
- 将jsp文件下拉列表中的选定项分配给一个java变量(比如String selection)
- 如何用时钟重复一个javascript函数
- 你如何使用JavaScript制作一个工作时钟
- 如何旋转时钟指针围绕一个点与createjs
- 我想为特定的时区创建一个javascript时钟
- Javascript -最好的两种方法来创建一个简单的时钟
- 我如何触发一个网站时钟从上午到下午正确
- 如何制作一个显示英国时间的时钟,但整个应用程序都是印度时间
- 在一个时钟中以五分钟为间隔绘制指示器
- 开始一个定时器时钟后,另一个和循环它使用javascript
- 我如何添加渐变的背景颜色在一个颜色时钟
- 编码一个时钟加速计算器