实用函数(一:无操作超时返回登录页)

382 阅读1分钟

今天看了一篇文章无操作超时返回登录页,感觉很实用,将其记录下来。思路:设置两个时间,一个是更新鼠标移动时(lastTime),另一个是获取现在的时间(currentTime),再将两者对比 设置currentTime超出lastTime多长时间 执行跳转登录页即可。啥话不说,上代码

方法一

来源于无操作超时返回登录页

let lastTime = new Date().getTime()
let currentTime = new Date().getTime()
const timeOut = 30 * 60 * 1000 // 设置超时时间: 30分钟
let timeRunning = window.setInterval(checkTimeout, 30 * 1000) // 设置监测时间:30s/次

window.onload = function () {
  window.document.onmouseover = function () {
    lastTime = new Date().getTime() // 更新lastTime
  }
  window.document.onclick = function () {
    lastTime = new Date().getTime() // 更新lastTime
  }
  window.document.onkeydown = function () {
    lastTime = new Date().getTime() // 更新lastTime
  }
  window.document.onmousewheel = function () {
    lastTime = new Date().getTime() // 更新lastTime
  }
}
 function checkTimeout () {
  currentTime = new Date().getTime() // 更新当前时间
  if (currentTime - lastTime > timeOut) { // 判断是否超时
    // 清除定时
    clearInterval(timeRunning)
    // 清除缓存
    window.localStorage.clear()
    // 跳到登陆页
    /* 跳转代码 */
  }
}

方法二

利用防抖动原理

var debounce = function(fun, delay) {
  let time = null
  return function() {
    let args = arguments
    clearTimeout(time)
    time = setTimeout(() => {
      fun.apply(this, args)
    }, delay)
  }
}
function handle() {
	// 返回登录页的代码
} 
window.onload = function() {
    const logOut = debounce(handle, 180000) // 设置超时时间
    logOut()
    document.body.addEventListener('click', logOut)
    document.body.addEventListener('keydown', logOut)
    document.body.addEventListener('mousemove', logOut)
    document.body.addEventListener('mousewheel', logOut)
}