0

I would like to setup a counter which can be paused as well as resumed with in a button click in javascript. But what ever i have tried can able to pause it but its not resuming from where i have paused, its starting from beginning when i perform resume operation.

below is my code what i have tried so far.

const [isPlay, setisPlay] = useState(true);
  const timerRef = useRef(null);



  useEffect(() => {

    start();
  }, []);

  var counter;

  function start() {
    console.log('start');
    if (!counter) {
      reset();
    } else {
      loop();
    }
  }

  function pause() {
    if (timerRef.current) {
      clearInterval(timerRef.current);
      timerRef.current = null;
    }
  }

  function reset() {
    console.log('reset');
    pause();
    counter = 10;
    loop();
  }

  function loop() {
    timerRef.current = setInterval(function () {
      if (0 >= counter) {
        pause();
        return;
      }
      console.warn('counter', counter);
      counter--;
    }, 1000);
  }

  const stopProgress = () => {
    if (isPlay) {
      pause();
      setisPlay(false);
    } else {
      start();
      setisPlay(true);
    }
  };

Can anyone please give me a solution for this to fix that. Answers would be much appreciated.

Thomas James
  • 187
  • 2
  • 16
  • Hey @Thomas. You can see this example on how to use interval properly for pause and resume purpose. https://stackoverflow.com/questions/21277900/how-can-i-pause-setinterval-functions – Owais Ahmed Khan Apr 22 '21 at 08:51
  • Is it something like this, you are trying to achieve? https://codesandbox.io/s/dreamy-gareth-ynz8y – secan Apr 22 '21 at 09:46
  • @secan Yes i tried this but its not updating the counter dynamically. could you tell me any way can i print that counter rather than putting it on the console. – Thomas James Apr 22 '21 at 21:43

0 Answers0