ReactJS - Using setInterval for decreasing timer - javascript

I am trying to create a timer application in react. The app works by calling a setInterval timer when the user clicks a button.
const [timer, setTimer] = useState(1500) // 25 minutes
const [start, setStart] = useState(false)
const onClick = () => {
if (!start) {
var tick = setInterval(() => {
setStart(true)
if (timer < 0) {
clearInterval(tick)
}
setTimer(timer => timer - 1)
console.log(timer)
}, 1000)
}
}
Even though the timer is decreasing every second, console.log(timer) still prints out 1500 and does not decrease. I am not able to stop the timer thereafter.

The set function is asynchronous, so the console.log does not have the new value yet.
Put the log inside the function setTimer:
...
setTimer(timer => {
console.log(timer - 1)
return timer - 1;
})
...

Related

setTimeout out of sync when closing site

setTimeout function works in line with my other setTimeout function as long as I keep the window open. However, if I go to another tab/window and then come back to the timer, it will be out of sync with the other countdown.
This is the first timer:
const [isDisabled, setIsDisabled] = useState(false);
const handleOnClickUp = () => {
setIsDisabled(true);
setTimeout(() => setIsDisabled(false), 60000);}
Second Timer:
const [counter, setCounter] = useState(60);
if (isDisabled == true) {
setTimeout(() => setCounter(counter - 1), 1000);
}
if (counter == 0) {
setCounter(60);
}
Returning:
return (
<>
<div>{counter}</div>
<button
disabled={isDisabled}
onClick={handleOnClickUp}
className="bg-gray-500"
>
Up
</button>
</>
);
TLDR: How can I sync the two timers together with no problems?
Chrome and most other browsers have low-priority execution when a tab is inactive, i.e., setCounter is not being called as frequently. I faced a similar issue a while back and then shifted to using requestAnimationFrame.
Here's the example code from React:
const countDown = 30 * 1000;
const defaultTargetDate = new Date().getTime();
const [targetDate, setTargetDate] = useState(new Date(defaultTargetDate));
const [remainingSeconds, setRemainingSeconds] = useState(countDown / 1000);
const countItDown = () =>
requestAnimationFrame(() => {
const diff = Math.floor((targetDate - new Date().getTime()) / 1000);
setRemainingSeconds(diff);
if (diff > 0) {
countItDown();
}
});
useEffect(() => {
countItDown();
}, [targetDate]);

Countdown Timer using functional component in ReactJS doesn't work properly

I want to make a countdown timer with start, stop, resume and reset buttons. However, I could not figure out why my code does not work. I am guessing that the issue lies in the part on timer, setInterval and clearInterval.
I have attached snippets of my code below.
Help would be greatly appreciated, thanks!
function Countdown() {
const [ timerRunning, setTimerRunning ] = useState(false);
const [ startTime, setStartTime ] = useState(0);
const [ totalTime, setTotalTime ] = useState(0);
var timer;
const startTimer = () => {
setTimerRunning(true);
setStartTime(totalTime);
setTotalTime(totalTime);
timer = setInterval(() => {
const remainingTime = totalTime - 1000;
if (remainingTime >= 0) {
setTotalTime(remainingTime);
} else {
clearInterval(timer);
setTimerRunning(false);
setStartTime(0);
setTotalTime(0);
}
}, 1000);
};
const stopTimer = () => {
clearInterval(timer);
setTimerRunning(false);
};
you have to put your setInterval in React.useEffect take a look at this post
some suggestions for your code:
use className instead of class attribute in your elements.
don't use var or let in react functional components.
useState doesn't change value immediately. So it's value is not actually changing. To avoid this use UseEffect hook.
useEffect(() => {
let intervalid
if (timerRunning){
intervalid = setInterval(() => {
const remainingTime = totalTime - 1000;
if (remainingTime >= 0) {
setTotalTime(remainingTime);
} else {
clearInterval(intervalid);
setTimerRunning(false);
setStartTime(0);
setTotalTime(0);
}
}, 1000);
}
return () => {
clearInterval(intervalid)
}
}, [timerRunning,totalTime])

How to pause a setInterval countdown timer in react?

I'm trying to build a pomodoro timer with a pause option. There's an analogue clock and a digital timer. My issue is with the digital timer - I can pause it by clearing the interval but do not know how to resume it without starting from the top (with a new setInterval).
This is the codesandbox of the project.
This is the relevant part from the DigitalClock component:
const timer = () => {
const now = Date.now()
const then = now + mode.duration * 60 * 1000
countdown = setInterval(() => { // That's how I resume it (with a re-render)
const secondsLeft = Math.round((then - Date.now()) / 1000)
if(secondsLeft < 0 || pause) {
clearInterval(countdown) // That's how I pause it (by clearing the interval)
return;
}
displayTimeLeft(secondsLeft)
}, 1000)
}
I think pausing the timer could be done with a boolean instead of clearing the interval,
So let's say that u have also a boolean keeping track of if it's paused on top level
let paused = false;
and you should consider looking up for if timer is not paused then do the math inside so
countdown = setInterval(() => { // That's how I resume it (with a re-render)
if(!paused) {
const secondsLeft = Math.round((then - Date.now()) / 1000)
if(secondsLeft < 0 || pause) {
clearInterval(countdown) // That's how I pause it (by clearing the interval)
return;
}
displayTimeLeft(secondsLeft)
}
}, 1000)
The only thing that's left is to toggle this paused boolean to true/false when someone click's the Pause button.
I don't know about React that much but that would be the choice I would go if i was doing this task :)
Possible solution - don't clear the interval when it is paused, just don't update the secondsLeft on the tick
Also, secondsLeft can be an integer, it doesn't have to be related to the actual time.
// global variables
var pause = false;
var elapsed, secondsLeft = 60;
const timer = () => {
// setInterval for every second
countdown = setInterval(() => {
// if allowed time is used up, clear interval
if (secondsLeft < 0) {
clearInterval(countdown)
return;
}
// if paused, record elapsed time and return
if (pause === true) {
elapsed = secondsLeft;
return;
}
// decrement seconds left
secondsLeft--;
displayTimeLeft(secondsLeft)
}, 1000)
}
timer();
const displayTimeLeft = (seconds) => {
document.getElementById("time").textContent = seconds;
}
document.getElementById("pause").addEventListener("click", (evt) => {
pause = !pause;
evt.target.textContent = pause ? "resume" : "pause";
if (pause === false) {
secondsLeft = elapsed;
}
});
<div id="time"></div>
<button id="pause">pause</button>
Using react, the timer should be in a useEffect hook (assuming you're using functional components). The useInterval will be placed inside and will run naturally within, updating the display through the useEffect hook. Place the clear interval in the useEffect return statement so when the timer expires, the interval will clear itself.
Then using pause as a state variable, manage your timer with buttons.
const [seconds, setSeconds] = useState(30);
const [pause, setPause] = useState(false);
useEffect(() => {
const interval = setInterval(() => {
if(!pause) { //I used '!paused' because I set pause initially to false.
if (seconds > 0) {
setSeconds(seconds - 1);
}
}
}, 1000);
return () => clearInterval(interval);
});
const handlePauseToggle = () => {
setPause(!pause);
}
Add a button to click, and your pause feature is set up.
*** Side note, feel free to ignore***
It looks like you have a way to display the time already, but I think it would be easier if you use the 'seconds' state variable in curly brackets to display your timer instead of creating a function (see below).
<div>
<p>0:{seconds >= 10 ? {seconds} : `0${seconds}`}</p>
</div>
This will display the timer correctly in a single line. Minutes is easy to add and so on.
Just a thought to make your code easier.
Using custom hook
Follow the following steps:
Create a new state variable to store the counter value on resume
On start check if you have a resume value then use it otherwise use the initial counter
Here's the full custom hook:
const useCountdown = ({ initialCounter, callback }) => {
const _initialCounter = initialCounter ?? DEFAULT_TIME_IN_SECONDS,
[resume, setResume] = useState(0),
[counter, setCounter] = useState(_initialCounter),
initial = useRef(_initialCounter),
intervalRef = useRef(null),
[isPause, setIsPause] = useState(false),
isStopBtnDisabled = counter === 0,
isPauseBtnDisabled = isPause || counter === 0,
isResumeBtnDisabled = !isPause;
const stopCounter = useCallback(() => {
clearInterval(intervalRef.current);
setCounter(0);
setIsPause(false);
}, []);
const startCounter = useCallback(
(seconds = initial.current) => {
intervalRef.current = setInterval(() => {
const newCounter = seconds--;
if (newCounter >= 0) {
setCounter(newCounter);
callback && callback(newCounter);
} else {
stopCounter();
}
}, 1000);
},
[stopCounter]
);
const pauseCounter = () => {
setResume(counter);
setIsPause(true);
clearInterval(intervalRef.current);
};
const resumeCounter = () => {
startCounter(resume - 1);
setResume(0);
setIsPause(false);
};
const resetCounter = useCallback(() => {
if (intervalRef.current) {
stopCounter();
}
setCounter(initial.current);
startCounter(initial.current - 1);
}, [startCounter, stopCounter]);
useEffect(() => {
resetCounter();
}, [resetCounter]);
useEffect(() => {
return () => {
stopCounter();
};
}, [stopCounter]);
return [
counter,
resetCounter,
stopCounter,
pauseCounter,
resumeCounter,
isStopBtnDisabled,
isPauseBtnDisabled,
isResumeBtnDisabled,
];
};
And here's an example of using it on codepen:
React useCountdown

How do I make setState work inside setInterval? (currently working-ish) [duplicate]

This question already has answers here:
State not updating when using React state hook within setInterval
(14 answers)
Closed 2 years ago.
function func(){
const [time, setTime] = useState(10);
var timeRemaining = 10;
const myInterval = setInterval(() => {
if (timeRemaining > 0) {
timeRemaining = timeRemaining - 1;
setTime(timeRemaining);
} else { clearInterval(myInterval) }
}, 1000);
return <div>{time}</div>
}
The code above works thanks to the variable timeRemaining. However, it stops working if I remove that variable (in order to keep the code clean):
const myInterval = setInterval(() => {
if (time> 0) { setTime(time-1); }
else { clearInterval(myInterval); }
}, 1000);
By rewriting it in the above way, it stops updating time.
Use effects to control interval, ref to hold reference to interval timer reference, and functional state update to correctly manage state.
Effect 1 - setup (mount) and cleanup (unmount) of interval effect
Effect 2 - clears interval when time reaches 0
Functional Component Code:
function App() {
const timerRef = useRef(null);
const [time, setTime] = useState(10);
useEffect(() => {
// Use pure functional state update to correctly queue up state updates
// from previous state time value.
// Store returned interval ref.
timerRef.current = setInterval(() => setTime(t => t - 1), 1000);
// Return effect cleanup function
return () => clearInterval(timerRef.current);
}, []); // <-- Empty dependency array, effect runs once on mount.
useEffect(() => {
// Clear interval and nullify timer ref when time reaches 0
if (time === 0) {
clearInterval(timerRef.current);
timerRef.current = null;
}
}, [time]); // <-- Effect runs on mount and when time value updates.
return <div>{time}</div>;
}
Use the function version of setTime, though I'd suggest putting your interval into a useEffect for cleanup as well
setTime((time) => {
if (time > 0) {
return time - 1;
}
clearInterval(myInterval);
return time;
});
With a useEffect for cleanup of the interval on unmount:
const {useState,useEffect} = React;
function Func() {
const [time, setTime] = useState(10);
useEffect(() => {
const myInterval = setInterval(() => {
setTime((time) => {
if (time > 0) {
return time - 1;
}
clearInterval(myInterval);
return time;
});
}, 1000);
return () => {
clearInterval(myInterval);
};
}, []);
return <div>{time}</div>;
}
ReactDOM.render(<Func />,document.querySelector('#root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"/>
The problem is that you're creating a new setInterval every time the component was recreated, as a consequence of setTime execution.
As an alternative to the other answers, that put the setInterval calling inside an useEffect, you can also switch to a setTimeout and not using the useEffect:
const App = (props) => {
const [time, setTime] = useState(10);
setTimeout(() => {
if (time > 0) {
setTime(time - 1);
}
}, 1000);
return <div>{time}</div>;
};
Every time the component is redrawn as an effect of setTime call, the setTimeout will be fired again.
function func(){
const [time, setTime] = useState(10);
var timeRemaining = 10;
const myInterval = setInterval(() => {
if (timeRemaining > 0) {
timeRemaining = timeRemaining - 1;
setTime(timeRemaining);
} else { clearInterval(myInterval) }
}, 1000);
return <div>{time}</div>
}
Here with every render, JS would start a setInterval. And in setInterval's callback, variable timeRemaining allocated for every render in respect get stored, or we call it CLOSURE. So 1 sec after the very beginning, REACT render func again. And thus you get another interval and a variable timeRemaining. It'll run from timeRemaining = 10.
setTime will always be one thing. And time will be read from HOOKS's pools.
This code is WRONG! You'll have more and more interval with its timeRemaining.

Timer does not actually stop after pause button is clicked

Timer is displayed as if it is kind of stop after pause button is clicked, but when i click resume i find out that counter continue to countdown behind the scene. I guess there are issues with setInterval. Please help me. My project on CodePen for reference if you need.
My timer function
function timer(seconds) {
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimerLeft(seconds);
console.log({
now,
then
});
countdown = setInterval(() => {
if (!isPaused) {
const remainSeconds = Math.round((then - Date.now()) / 1000);
if (remainSeconds < 0) {
clearInterval(countdown);
return;
}
displayTimerLeft(remainSeconds);
}
}, 1000);
}
Pause and start click events
pause.addEventListener('click', function() {
isPaused = true;
return;
})
start.addEventListener('click', function() {
isPaused = false;
})
Looking at your code, I suppose the problem is you keep the same then value, which is ultimately a timestamp at which the timer should end. Right now, instead of pausing the countdown, you stop the display from changing.
I would advise using your variable seconds instead (and calculating display using modulo %), and decreasing it every second. That way, pausing the display would effectively pause the decreasing.
Keep a reference of the current time and manually add a second at each tick.
function timer(seconds) {
clearInterval(countdown);
const t = new Date();
const end = t.getTime() + seconds * 1000;
displayTimerLeft(seconds);
console.log({
t,
end
});
countdown = setInterval(() => {
if (!isPaused) {
const remainSeconds = Math.round((end - t.getTime()) / 1000);
if (remainSeconds < 0) {
clearInterval(countdown);
return;
}
displayTimerLeft(remainSeconds);
t.setSeconds(t.getSeconds() + 1);
}
}, 1000);
}
Demo: http://codepen.io/miguelmota/pen/wgMzXY
setInterval returns a unique id that can be used to stop the timer using clearInterval:
var id = setInterval(function(){
console.log('running every 300 ms');
},300);
clearInterval(id) // stop timer

Categories