简体   繁体   中英

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
    }
  }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM