/

js中的定时器应用

setTimeOut的使用

每一分钟执行一次,大神都喜欢用setTimeOut,而不是setInterVal,因为setTimeOut可以更好的指定时间间隔,防止拥堵。

1
2
3
4
5
6
7
8
9
10
interval (fn1) { this.timer = setTimeout(() => { if (this.timer !== null) { clearTimeout(this.timer) this.timer = null } fn1() this.interval(fn1) }, 1000 * 60) }

如果是操作dom的操作,最好使用 requestAnimationFrame,

1
2
3
4
5
6
7
8
9
10
11
12
interval (fn1) { this.timer = setTimeout(() => { if (this.timer !== null) { clearTimeout(this.timer) this.timer = null } requestAnimationFrame(() => { fn1() this.interval(fn1) }) }, 1000 * 60) }

当销毁页面时,别忘了取消定时

1
2
3
4
5
6
beforeDestroy () { if (this.timer) { clearTimeout(this.timer) this.timer = null } },

每天固定时间点执行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function interval(fn,{h=2,m=30,s=0}={h:5,m:30,s:00}){ let curTime = new Date() let targetTime = new Date() targetTime.setHours(h) targetTime.setMinutes(m) targetTime.setSeconds(s) time = curTime - targetTime timer = setTimeout(()=>{ if(time !== null){ clearTimeout(timer) timer = null } fn() interval(fn,{h,m,s}) }, time<0?time:1000*60*60*24-time) }
作者:liuk123标签:js分类:javascript

本文是原创文章,采用 CC BY-NC-ND 4.0 协议, 完整转载请注明来自 liuk123