Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
Does a function executing a setTimeout get canceled using clearTimeout?

I have a timer stored in an object inside a React component. What I try to do is cancel the timer before the component gets unmounted. Will my code work? How can I check it?

Constructor of the component:

constructor() {
    super();
    this.formRef = React.createRef();
    this.redirectTimer = {
        timer: () => {
            setTimeout(() => {
                this.props.history.push("/");
            }, TIME_UNTIL_REDIRECT)
        }
    };
}

Call of clearTimeout:

componentWillUnmount() {
    clearTimeout(this.redirectTimer.timer);
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

setTimeout returns the unique ID of the timer. You should store it and use it to clear the timeout.

constructor() {
    super();
    this.formRef = React.createRef();
    this.timerID = null;
    this.redirectTimer = {
        timer: () => {
           this.timerID = setTimeout(() => {
                this.props.history.push("/");
            }, TIME_UNTIL_REDIRECT)
        }
    };
}
componentWillUnmount() {
    clearTimeout(this.timerID );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

that is not the proper way to clear a timeout, the clearTimeout function expects an id of a timer, and the function setTimeout returns that id, in your case you have the object:

{
    timer: () => {
        setTimeout(() => { this.props.history.push("/");}, TIME_UNTIL_REDIRECT)
    }
}

basically when you execute timer() it will run the function, but you are not storing the timerId on any place.

your code will clear the timeout with something like this:

constructor() {
    super();
    this.formRef = React.createRef();
    this.timerId;
    this.redirectTimer = {
        timer: () => {
            this.timerId = setTimeout(() => {
                this.props.history.push("/");
            }, TIME_UNTIL_REDIRECT)
        }
    };
}

////// other code

componentWillUnmount() {
    clearTimeout(this.timerId);
}

you can test that with your code you are not clearing the timeout if you put a console.log inside the timeout, if you leave the page at some point you will see something logged, this is because the timer was running.... with the same test you can check with the fixed code that it will not log anything.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda