优秀的编程知识分享平台

网站首页 > 技术文章 正文

setTimeout定时器不准,卡顿白屏怎么解决?

nanyue 2024-08-10 18:38:51 技术文章 9 ℃
在企业里面做项目,经常会需要使用定时器,但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)
}
最近发表
标签列表