Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!