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

134
Views
Toggle button using a flag React

When a button is pressed, it calls the toggleTimer() function. Now, when I press this button, it pauses immediately, however when I press the button a second time, it does not unpause immediately. The goal is to get the button to toggle between these 2 states immediately after being pressed.

When I run the program I notice weirdly that I have to press my button many times before I get the unpause behaviour to work. I think this is due to the let paused=true global variable, but I'm unsure how to solve this.

///////PAUSE TIMER/////////////////
  let paused = true;
  let holdValue;

  function toggleTimer(){
    if (paused===true){ // if paused, we clear timer and save value
      paused = false; 
      holdValue= remainingTime;
      clearInterval(timerRef.current);
    } else if (paused===false) { //if not paused, we can restart timer using our saved value
      paused = true; 
      startTimer(); // call our function to start timer
      setRemainingTime(holdValue); // update the remaining time using our saved value
    }
  }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I believe you are right about the global var making the behaviour weird.

So solution is to use a state in your button component:

const [paused, setPaused] = useState(false)

Then you should combine it with a useEffect that will handle the timer (I'm not sure I understood correctly but you should be able to adapt it to your need):

const Example = () => {
  const [paused, setPaused] = useState(false);

  useEffect(() => {
    let timer;
    if (!paused) {
      timer = setInterval(() => {
        // Do something
      }, 10000);
    } else {
      clearInterval(timer);
    }

    return () => clearInterval(timer);
  }, [paused]);

  return <Button onClick={() => setPaused(!paused)}>Button</Button>;
};

Here when paused is false, the timer (interval) will call execute its callback (// Do something) every 10s, then when you click on the button paused change to false so the useEffect is executed and the time it clear the timer. If you want to start it again, then click and the button, that will change the paused state and the useEffect will restart the interval.

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