8

Github GitHub - littlee/eslint-plugin-clean-timer: eslint plugin for best practi...

 3 years ago
source link: https://github.com/littlee/eslint-plugin-clean-timer
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

中文文档

eslint-plugin-clean-timer

Enforce best practice with setTimeout and setInterval

Motivation

It is always easy to forget to clear the timers set up by setTimeout or setInterval, which can cause bugs that are uneasy to find out.

Image a component with onMount and onUnmount life cycles, in the code below, if the component is mounted and unmounted within 1000ms, the timer will still fire

class App {
  onMout() {
    /* timer id should assign to an identifier or member for cleaning up,
      `let timer = setInterval()` */
    setInterval(() => {}, 1000);
    /* ^^^^^^^^^^^^^^^^^^^^^^^^ */
  }
}

The best practice is to clear the timer whenever we don't need it any more.

This ESLint plugin can warn you when you are setting up any timers need to be cleared.

class App {
  onMout() {
    this.timer = setInterval(() => {}, 1000);
  }
  onUnmount() {
    clearInterval(this.timer);
  }
}

Installation

npm install eslint-plugin-clean-timer --save-dev

Usage

Add clean-timer to your eslint configuration file

{
  "plugins": ["clean-timer"],
  "rules": {
    "clean-timer/assign-timer-id": 2
  }
}

Examples

timer need to be cleared

setTimeout(() => {}, 1000);
setInterval(() => {}, 1000);
setInterval(() => {}, 0);
setInterval(() => {});

timer not need to be cleared

setTimeout(() => {}, 0);
setTimeout(() => {});

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK