javascript 如何写一个定时器

我们都知道,JavaScript 中有两种定时器, 这上面我所使用到的是setInterval(),setInterval() 定时器和 setTimeout() 理论一样,区别在于 setInterval() 每隔一段时间就会给队列添加一个定时任务。我们在使用的时候一定要清除定时器,不然会导致定时器一直运行.

它们两者的区别:

  • setTimeout():指定时间后执行一段代码(延迟执行)。

  • setInterval():每隔一段时间执行一段代码(间隔执行)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

// 定时器标识
timer:null,
// 超时间隔
timeOut: 5 * 1000,
// 最后时间
lastTime:new Date().getTime(),
// 当前时间
currentTime:new Date().getTime(),

/**
* 开始监听
*
* @param callback callback 超时回调
*/
start: function(callback) {
localStorage.setItem("lastTime", this.lastTime)

// 鼠标按下时, 更新最后时间, 保障不超时
window.document.ontouchstart = function() {
localStorage.setItem("lastTime",new Date().getTime())
}

// 定时检查是否超时
this.timer = setInterval(() => {
this.currentTime = new Date().getTime() // 更新当前时间
this.lastTime = localStorage.getItem("lastTime");
if (this.currentTime - this.lastTime > this.timeOut) { // 判断是否超时
// 超时了
callback()
localStorage.setItem("lastTime", new Date().getTime())
}
}, 1000)
},

/**
* 清除定时器
*/
clear: function() {
if (this.timer) {
clearInterval(this.timer)
}
}


javascript 如何写一个定时器
http://example.com/2023/06/06/javascript/index_4/
作者
李仁珍
发布于
2023年6月6日
许可协议