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.