js中的定时器应用

setTimeOut的使用

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interval(time: number = 3000, callback:Function){ let t:any = null const fn = (time: number = 3000, callback:Function)=>{ callback() t = setTimeout(()=>{ fn(time, callback) },time) } fn(time, callback) return { stop: () => { clearTimeout(t) t=null } } }

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

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

如果频繁的操作dom,用requestAnimationFrame可以减少渲染损耗,防止页面抖动。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
requestAnimationFrame(()=>{}) const element = document.getElementById('div'); let start; function step(timestamp) { if (start === undefined) start = timestamp; const elapsed = timestamp - start; //这里使用`Math.min()`确保元素刚好停在200px的位置。 element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)'; if (elapsed < 2000) { // 在两秒后停止动画 window.requestAnimationFrame(step); } } window.requestAnimationFrame(step);

rxjs的定时器

angular结合rxjs可以更加简单优雅的实现,而且可以减少内存消耗。 当页面稳定之后, 执行 timer操作

1
2
3
4
5
6
7
8
9
10
private appRef = inject(ApplicationRef) interval(time:number=3000){ return concat( this.appRef.isStable.pipe(first(isStable => isStable === true)), timer(time, time) ).pipe( takeUntilDestroyed(this.destoryRef) ) }

每天固定时间点执行

每次执行完之后,需要再次计算下一次执行的时间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function interval(fn,{h=2,m=30,s=0}={h:5,m:30,s:0}){ let curTime = new Date() let targetTime = new Date() targetTime.setHours(h) targetTime.setMinutes(m) targetTime.setSeconds(s) let time = targetTime-curTime console.log(time) let timer = setTimeout(()=>{ fn() timer = interval(fn,{h,m,s}) }, time>0?time:1000*60*60*24 + time) return timer }