js中的定时器应用 {#h_js中的定时器应用}
setTimeOut的使用 {#h_settimeout的使用}
每一分钟执行一次,大神都喜欢用setTimeOut,而不是setInterVal,因为setTimeOut可以更好的指定时间间隔,防止拥堵。
interval (fn1) {
this.timer = setTimeout(() => {
if (this.timer !== null) {
clearTimeout(this.timer)
this.timer = null
}
fn1()
this.interval(fn1)
}, 1000 * 60)
}
如果是操作dom的操作,最好使用 requestAnimationFrame
,
interval (fn1) {
this.timer = setTimeout(() => {
if (this.timer !== null) {
clearTimeout(this.timer)
this.timer = null
}
requestAnimationFrame(() => {
fn1()
this.interval(fn1)
})
}, 1000 * 60)
}
当销毁页面时,别忘了取消定时
beforeDestroy () {
if (this.timer) {
clearTimeout(this.timer)
this.timer = null
}
},
每天固定时间点执行 {#h_每天固定时间点执行}
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)
}