在企业里面做项目,经常会需要使用定时器,但setTimeout定时器不准,时间久了后,
会卡住屏幕不动,时间走的也不准,怎么解决避免呢?
用window.setInterval和setTimeout组合起来使用,内部用setTimeout('你的业务函数', 0)来包裹。
下面是一企业案例,用来实时判断网站是否需要系统维护。
import Vue from 'vue'
let defaultT = window.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
function ifMaintain () {
localStorage.removeItem('memoInfo')
Vue.prototype.$http({
url: Vue.prototype.$http.url('mt-cloud' + '/api/sn.biz.maintain'),
method: 'post',
timeout: 60 * 1000,
data: Vue.prototype.$http.data({
'method': 'sn.biz.maintain',
'params': {
sn: Vue.cookie.get('SN')
}
})
}).then((res) => {
if (!res.data.error) {
let {startTime, endTime, flag, userMemo} = res.data.result
Vue.cookie.set('maintain', flag)
Vue.cookie.set('startTime', startTime || defaultT)
Vue.cookie.set('endTime', endTime || defaultT)
Vue.cookie.set('userMemo', userMemo || '')
localStorage.setItem('memoInfo', userMemo || '')
}
}).catch(() => {})
}
ifMaintain()
let routrpath = window._ROUTER.history.current.fullPath
if (routrpath === '/maintain') {
clearInterval(window.anotherPageInterval)
window.isMaintainPageInterval = window.setInterval(() => {
setTimeout(ifMaintain, 0)
}, 1000 * 5)
} else {
clearInterval(window.isMaintainPageInterval)
window.anotherPageInterval = window.setInterval(() => {
setTimeout(ifMaintain, 0)
}, 1000 * 30)
}