vue中在离开页面后优雅的自动销毁定时器~不再担心setTimeout、setInterval还在不断执行~

287 阅读1分钟

说明

此教程以vue3作为示例,理论上在vue2、uniapp(vue项目中)都可以使用,在调用的组件销毁后自动销毁定时器,不需要手动销毁,比如手动调用clearInterval和clearTimeout对定时器进行销毁

解决场景

一般的延迟任务和循环任务、http请求后循环任务和延迟任务、事件回调延迟任务等

在线示例

stackblitz.com/edit/vitejs…

安装和使用

安装tools-javascript工具库,此仓库提供了定时器、http请求、websocket、cookie的功能

npm install tools-javascript

安装完成后在main.js或ts文件中写入:

import 'tools-javascript'
  • 创建 Util.ts文件,内容:

export default class Util {

  //方案1-判断组件是否存在于dom中
  static Timer = () => {
    const findTopTag = (el: any, tag: string = 'html'): any => {
      if (!el?.parentElement) return null;
      if (el.parentElement.tagName.toLocaleLowerCase() === tag)
        return el.parentElement;
      else return findTopTag(el.parentElement, tag);
    };
    const timer = new TimerBean();
    const _vm = getCurrentInstance();
    timer.vm = () => () => findTopTag(_vm?.vnode.el?.parentElement);
    return timer;
  };

  //方案2-判断组件是否被真正的销毁
  static Timer = () => {
    const timer = new TimerBean();
    const _vm = getCurrentInstance();
    timer.vm = () => () => !_vm!.isUnmounted;
    return timer;
  };
}

  • 在任意vue文件使用

import Util from './Util'

const timer = Util.Timer()

//延迟2秒后执行
timer.once(() => {
    console.log(1)
    //延迟2秒后执行
    timer.once(() => {
        console.log(2)
        //延迟2秒后执行
        timer.once(() => {
            console.log(3)
        }, 2000)
    }, 2000)
}, 2000)

//每2秒执行一次
timer.on(() => {
    console.log('test定时2秒执行')
}, 2000)