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

196
Visualizações
How can I clear Interval in React?

I am using setInterval on react redux. Below is my function.

FileAction.js

export const SetPath = ({ path, location }) => async (dispatch) => {
    try {
        let interval;
        if (pre_path === path) {
            interval = setInterval(() => {
                handler(path);
            }, 3000);
        } else {
            pre_path = path;
            clearInterval(interval);
        }

        const handler = async (pth) => {
            const mtime = await axios.post('/api/file', { data: pth });
            dispatch({
                type: GET_EVENT,
                payload: { time: mtime, position: location }
            });
        }
    } catch (err) {
        dispatch({
            type: GET_ERROR
        });
    }
};

What I would like to do is when I call SetPath function, it have to fetch data from api/file every 3 secs.

But now when I pass another path to SetPath function, it dulicate interval.

How can I implement this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are defining the interval variable inside setPath function, therefore the variable will be reinitialized everytime setPath is executed. Try defining it outside the function. You may need to use useRef in order to not lose the variable when a re-render occurs.

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