timer-manager-lib
Version:
JS实现的一个定时任务管理器
124 lines (91 loc) • 3.1 kB
Markdown
JS based on a timing task manager, can be used in the Node and browser environment, you can easily add, delete, start, stop and clear timers, use the same interval to manage the global timer, as far as possible to avoid the complexity of multiple different tasks and maintenance difficulty, time interval diversity, Achieve the effect of time-indexed function cache
1. pnpm i
2. pnpm dev
3. pnpm build
1. Installation
```bash
npm install timer-manager-lib
yarn add timer-manager-lib
pnpm install timer-manager-lib
```
2. Introduce the timer-manager-lib module into the code
```javascript
import { TimerManager } from "timer-manager-lib";
```
```javascript
const { TimerManager } = require("timer-manager-lib");
```
```html
<script src="./node_modules/timer-manager-lib/dist/umd/index.js"></script>
<script>
console.log(TimerManager);
</script>
```
3. Create a Timer instance
```javascript
const timerManager = new TimerManager({
type: "interval", // interval Polling timer or frame Frame timer
autoStop: true, // Automatically stops the timer when there is no handle
});
```
4. Add a timer
Use the 'add' method to add a timer. It accepts a callback function (' handle ') and a delay time:
```javascript
const handle = () => {
console.log(" Timer trigger ");
};
const delay = 1000; // Time is measured in milliseconds
const timer = timerManager.add(handle, delay);
```
5. Delete the timer
Use the 'delete' method to delete a timer. The parameter provides the timer object to add the timer:
```javascript
timerManager.delete(timer);
```
6. Clear all timers
Use the 'clear' method to stop and clear all timers:
```javascript
timerManager.clear();
```
7. Automatically stop
By default, the autoStop option is set to true. This means that the timer stops automatically when there are no handlers (handlers are empty). To disable this behavior, set 'autoStop' to 'false' at initialization.
8. Comprehensive usage
```javascript
// Create a timer manager instance
const timerManager = new TimerManager();
// Record the execution step
let count = 0;
// Add a timer item and delete it after executing it once
const timer = timerManager.add(() => {
timerManager.delete(timer);
console.log(performance.now(), "del timer", count++);
}, 1000);
// Delay Add a timer item and reset it after three times
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);
```
https://gitee.com/DieHunter/timer-manager-lib
1. Fork the local warehouse
2. Star Warehouse
3. Make suggestions
4. Create a Pull Request