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

87
Visualizações
why is my gloval setInterval ID variable unavailable to a function?

I am writing a simple timer app and using setInterval for the first time. The project is in react typescript and I use the useReducer hook to manage state.

The project requires two separate timers, session and break, which may explain some of the code. The project also requires one button to start and stop the timer, hence I am using a single function.

I have redacted my reducer and types as the problem, as i understand, does not involve them, but some simple use of setInterval that I just don't get yet.

When the startStopTimer function is called a second time, the intervalID is undefined, even though it is declared globally.

const App = () => {
    const [timerState, dispatch] = useReducer(timerStateReducer, initialTimerState
    );

    let intervalID: NodeJS.Timer;

    const startStopTimer = () => {
        let name: string = timerState.session.count !== 0 ? 'session' : 'break';
        
        if (timerState[name].running) {
            console.log('stopping timer' + intervalID);
            //reducer sets running boolean variable to false
            dispatch({type: ActionKind.Stop, name: name});
            clearInterval(intervalID);
        } else {
           //reducer sets running boolean variable to true
            dispatch({type: ActionKind.Start, name: name}); 
            intervalID = setInterval(() => {
                dispatch({type: ActionKind.Decrease, name: name});
            }, 1000);
        }
    };

return (
      //redacted JSX code
       <button onClick={startStopTimer}>Start/Stop</button>
)
 

I have tried passing onClick as an arrow function (rather than a reference, i think?) and it behaves the same. I tried simplifying this with useState, but came across a whole 'nother set of issues with useState and setInterval so I went back to the useReducer hook.

Thanks!

about 4 years ago · Juan Pablo Isaza
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