Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda