前往Github获取本文源码。
相信setInterval
这个东西大火都比较熟了,这里不做关于它的介绍,而是关于本文是如何实现这一功能。
我们通过一个Set
来保存定时器的id
,当清除时,就把这个id
删掉;当每一次调用时,都会检查一下当前id
是否存储于这个Set
中。
如下:
const interval = {
_active: new Set(),
_id: 0,
set(callback, delay) {
const id = this._id++
this._active.add(id)
const handler = () => {
if (!this._active.has(id)) {
return
}
setTimeout(() => {
callback()
handler()
}, delay)
}
handler()
return id
},
clear(id) {
this._active.delete(id)
}
}
我们用_active
这个属性来保存上文提到过的id
,其它的就没什么要说的了。
用下面的代码测试它的正确性:
let count = 0
const id = interval.set(() => {
count++
console.log(`count is ${count}`)
if (count === 5) {
interval.clear(id)
}
}, 500)
一般定时器都是自己把自己clear
掉,这里也不例外,这种需求应该还挺多的。
这篇文章写着玩的,实际用途没啥用,只是说明了setInterval
可以基于setTimeout
来实现。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有