1.0.2 • Published 3 months ago

timer-manager-lib v1.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
3 months ago

timer-manager-lib

介绍

基于 JS 实现的一个定时任务管理器,可以在 Node 和浏览器环境下使用,你可以轻松地添加、删除、启动、停止和清除定时器,使用同一个 interval 管理全局的 timer,尽可能规避了多个不同的任务复杂性和维护的难度,时间间隔多样性,达到以时间为索引的函数缓存的效果

调试教程

  1. pnpm i
  2. pnpm dev
  3. pnpm build

使用说明

  1. 安装
   npm install timer-manager-lib
   yarn add timer-manager-lib
   pnpm install timer-manager-lib
  1. 在代码中引入 timer-manager-lib 模块
ESModule
import { TimerManager } from "timer-manager-lib";
Commonjs
const { TimerManager } = require("timer-manager-lib");
UMD
<script src="./node_modules/timer-manager-lib/dist/umd/index.js"></script>
<script>
  console.log(TimerManager);
</script>
  1. 创建一个 Timer 实例
const timerManager = new TimerManager({
  type: "interval", // interval 轮询定时器或 frame 帧定时器
  autoStop: true, // 当没有句柄时自动停止定时器
});
  1. 添加定时器

使用 add 方法添加定时器。它接受一个回调函数 (handle) 和一个延迟时间:

const handle = () => {
  console.log("定时器触发");
};
const delay = 1000; // 时间以毫秒为单位
const timer = timerManager.add(handle, delay);
  1. 删除定时器

使用 delete 方法删除某项定时器,参数提供添加定时器的 timer 对象:

timerManager.delete(timer);
  1. 清除所有定时器

使用 clear 方法停止并清除所有定时器:

timerManager.clear();
  1. 启动、暂停对应 delay 的定时器

使用 startTimerstopTimer 对某个 interval 启动、暂停:

const timerManage = new TimerManager();
const { timers } = timerManage;
const timer1 = timerManage.add(() => {
  console.log("hello");
}, 1000);
timerManage.add(() => {
  console.log("阿宇的编程之旅");
}, 1000);
const { delay } = timer1;
timerManage.stopTimer(timers[delay]); // 暂停定时器
setTimeout(() => {
  timerManage.startTimer(timers[delay]); // 1.5秒后启动定时器
}, 1500);
  1. 自动停止

默认情况下,autoStop 选项设置为 true。这意味着当没有句柄(timer 的 handlers 为空)时,定时器将自动停止。如果要禁用此行为,请在初始化时将 autoStop 设置为 false

  1. 综合用法
// 创建定时器管理器实例
const timerManager = new TimerManager();
// 记录执行步骤
let count = 0;
// 添加定时器项,执行一次后删除
const timer = timerManager.add(() => {
  timerManager.delete(timer);
  console.log(performance.now(), "del timer", count++);
}, 1000);
// 延时添加定时器项,执行3次后重置
setTimeout(() => {
  console.log(performance.now(), "timer2 start");
  timerManager.add(() => {
    console.log(performance.now(), "timer2", count++);
    if (count > 3) {
      timerManager.clear();
      console.log(performance.now(), "clear");
    }
  }, 1000);
}, 2000);
timerManager.add(() => {
  console.log(performance.now(), "timer3");
}, 500);

更多 TS 类型及源码注释参考

https://gitee.com/DieHunter/timer-manager-lib

参与贡献

  1. Fork 本仓库
  2. Star 本仓库
  3. 提出建议
  4. 新建 Pull Request
1.0.2

3 months ago

1.0.1

3 months ago

1.0.0

3 months ago