js监听在当前页面停留太长时间

// 使用

// 引用方法
<script src="./longTimeStopScreen.js"></script>
<script>
  window.onload = () => {
    // 定义倒计时的时长
    const time = 10;
    longTimestopScreen(true, time, fn);

    // 执行函数(回调函数)
    function fn(params) {
      if (window.confirm('你已经停留很久了,是否重新登录!')) {
        // 点击了确认 -- 清除定时器
        longTimestopScreen(false);
        // 执行其他操作逻辑
        console.log('确认', window.LTimer);
      } else {
        // 点击了取消 -- 重置定时器重新倒计时
        // stopMove(true, time, fn);
        console.log('取消', window.LTimer);
      }
    }
  };
</script>

// 方法

/*
 * @Description: ------ 文件描述 ------
 * @Creater: snows_l [email protected]
 * @Date: 2022-12-05 15:50:37
 * @LastEditors: snows_l [email protected]
 * @LastEditTime: 2022-12-05 16:09:39
 * @FilePath: /js/longTimeStopScreen.js
 */
/**
 * @description: 倒计时函数/清定时
 * @param { Boolean } isTime 是否倒计时/清空倒计时
 * @param {*} time 倒计时时间
 * @param {*} callback 倒计时之后的回调
 * @return {*} null
 * @demo longTimestopScreen(true, time, () => {
 *         console.log('倒计时时间到了')
 *       })
 */
function longTimestopScreen(isTime, time, callback) {
  let backUpTime = time;

  if (isTime) {
    // 定义全局定时器Id
    window.LTimer = null;
    // 加载就开始倒计时
    customInterval(time, callback);

    // 检测鼠标移动事件 ==> 当注销事件的时候必须注销的是同一个函数需要这么写
    window.addEventListener('mousemove', mouseEvent);
    // 鼠标事件
    function mouseEvent(e) {
      // 鼠标移动就重置定时器重新倒计时
      customInterval(time, callback);
    }

    /**
     * @description: 倒计时函数/清定时
     * @param {*} time 倒计时时间
     * @param {*} callback 倒计时之后的回调
     * @return {*} null
     * @demo customInterval(true, time, () => {
     *         console.log('倒计时时间到了')
     *       })
     */
    function customInterval(time, callback) {
      if (window.LTimer) clearInterval(window.LTimer);
      window.LTimer = setInterval(() => {
        time--;
        console.log('倒计时', time);
        if (time == 0) {
          time = backUpTime;
          callback();
        }
      }, 1000);
    }
  } else {
    // 移除监听事件并清除定时器(释放性能)
    window.removeEventListener('mousemove', mouseEvent);
    clearInterval(window.LTimer);
    window.LTimer = null;
  }
}

猜你喜欢

转载自blog.csdn.net/snows_l/article/details/129143792