T
T
testtostertest1112019-01-18 11:11:38
JavaScript
testtostertest111, 2019-01-18 11:11:38

How to clear a timer written through a promise when switching to another component in React?

const timer = new Promise(resolve => setTimeout(resolve, 5000));

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2019-01-18
@testtostertest111

class Hello extends React.Component {
  componentWillUnmount() {
    if (this.timer) {
      clearTimeout(this.timer);
    }
  }

  someMethod() {
    return new Promise((resolve) => {
      this.timer = setTimeout(resolve, 5000);
    });
  }
}

A
Andrey Okhotnikov, 2019-01-18
@tsepen

In componentWillUnmount lifecycle method use AbortController

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question