J
J
JeyFom2021-04-19 17:56:06
React
JeyFom, 2021-04-19 17:56:06

How to properly clear one of the timeouts?

There is a code like this:

componentDidMount() {
  this.foo = () = {

    //some code

    setTimeout(func, 1);
  };
};

componentWillUnmount() {
  setTimeout(func, 1);

  //some code

  this.foo();
}

How to properly clear one of the timeouts so that they do not stack, and both times the function was called after the interval?
If I do so
componentWillUnmount() {
  const timeout = setTimeout(func, 1);

  //some code

  clearTimeout(timeout);
  this.foo();
}

then the timeout is cleared before the function should be called

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2021-04-19
@Casufi

The example is too synthetic.
componentWillUnmount as well as componentDidMount are guaranteed to be called once.
The this.foo function is called in componentWillUnmount without conditions. What's the point of separating implementation and execution? Tell me what problem you are trying to solve, then you won’t have to write crutches

componentDidMount() {
  this.foo = (timerToClear) = {

    //some code
    if (timerToClear) {
      clearTimeout(timerToClear);
    }
    setTimeout(func, 1);
  };
};

componentWillUnmount() {
  const timer = setTimeout(func, 1);

  //some code

  this.foo(timer);
}

A more realistic example is when you set a timer to change a state, but this is more beautifully implemented on the useEffect hook with clearing
https://reactjs.org/docs/hooks-effect.html#effects...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question