TL; DR (Too long to see version)

Please use the github.com/littlee/esl…

background

In asynchronous JavaScript programming, authors often write various bugs, among which the most common errors are caused by forgetting to clear timers created by setTimeout or setInterval.

Consider the following code for a simple React component

import { useEffect, useState } from 'react';
function App() {
  const [sec, setSec] = useState(0);
  useEffect(() = > {
    setInterval(() = > {
      setSec((s) = > s + 1);
    }, 1000); } []);return <p>{sec}</p>;
}
Copy the code

Once the component is mounted, it increments the value of SEC by one every second, which seems fine, but the timer created by setInterval continues to run when the component is unmounted.

Experienced readers should immediately think that we can fix this problem by clearing the timer in the function returned by useEffect.

The improved code looks like this:

import { useEffect, useState } from 'react';
function App() {
  const [sec, setSec] = useState(0);
  useEffect(() = > {
    let timer = setInterval(() = > {
      setSec((s) = > s + 1);
    }, 1000);
    return () = > {
      clearInterval(timer); }; } []);return <p>{sec}</p>;
}
Copy the code

The problem is solved perfectly at this point, but for beginners, it is often not discovered until you run the code, and similar errors are often missed in environments where developer debugging tools are not available (such as mobile WebView).

At this point, interested readers can try to search the source code of one of their own projects in the editor, ifsetIntervalclearIntervalIf the number of search results is not equal, then the project is likely to hide similar errors, and the same appliessetTimeoutclearTimeout.

So the authors developed an ESLint plug-in that eliminates such errors while the project is coding.

The solution

eslint-plugin-clean-timer

Github package address: github.com/littlee/esl…

use

First, install and initialize ESLint in the project directory (skip this step if you already have an ESLint configuration)

npm i -D eslint
npx eslint --init
Copy the code

Step 2: Install eslint-plugin-clean-timer

npm i -D eslint-plugin-clean-timer
Copy the code

Add the following configuration to the ESLint configuration, please refer to eslint.org/docs/user-g…

{
  "plugins": ["clean-timer"]."rules": {
    "clean-timer/assign-timer-id": 2}}Copy the code

At this point, open the file with the timer code and see that the editor will prompt you for the relevant code. In the case of VSCode, you need to install the ESLint extension

If the configuration file changes do not take effect, try pressing Command(Ctrl)+Shift+P to find the ESLint: Restart ESLint Server Command in the panel that pops up and press Enter to execute it

ESLint also provides thoughtful fixes by clicking on the Quick Fix provided by ESLint… Execute the first option to automatically insert an assignment statement