Visit my Blog for the original post: How to Create a Simple React Countdown Timer
A Few Words in Front
Today I am going to share one interesting and useful small front-end feature implementation in React, a simple count down timer.
Solution
The correct implementation can be found at simple-react-countdown-timer if you wish to implement quickly without reading through my explanation.
import * as React from "react";
import { render } from "react-dom";
import "./styles.css";
function App() {
const [counter, setCounter] = React.useState(60);
// First Attempts
// setInterval(() => setCounter(counter - 1), 1000);
// Second Attempts
// React.useEffect(() => {
// counter > 0 && setInterval(() => setCounter(counter - 1), 1000);
// }, []);
// Second Attempts - Inspection
// React.useEffect(() => {
// counter > 0 &&
// setInterval(() => {
// console.log(counter);
// setCounter(counter - 1);
// }, 1000);
// }, []);
// Third Attempts
// React.useEffect(() => {
// const timer =
// counter > 0 && setInterval(() => setCounter(counter - 1), 1000);
// return () => clearInterval(timer);
// }, [counter]);
// Suggested by Laurent
React.useEffect(() => {
counter > 0 && setTimeout(() => setCounter(counter - 1), 1000);
}, [counter]);
return (
<div className="App">
<div>Countdown: {counter}</div>
</div>
);
}
const rootElement = document.getElementById("root");
render(<App />, rootElement);
Explanation
First attempt, in an intuitive way
Initially, we utilise useState
react hook to create a new state variable counter
in the functional component. counter
holds the number of seconds the counter should start with. Then a native JavaScript function, setInterval
is called to trigger setCounter(counter - 1)
for every 1000ms. Intuitively, it represents the number decreases by 1 every 1 second.
function App() {
const [counter, setCounter] = React.useState(60);
// First Attempts
setInterval(() => setCounter(counter - 1), 1000);
return (
<div className="App">
<div>Countdown: {counter}</div>
</div>
);
}
However, it works, in a terrible way. You can clearly notice that Initially the countdown works fine but then start to gradually accelerate.
That is because every time when setCounter
is triggered, the App
component get re-rendered. As the component is re-rendered, the App()
function is executed again, therefore, the setInterval()
function triggers again. Then there are 2 setInterval()
running at the same time and both triggering setCounter()
, which again, creates more setInterval()
.
Therefore, more and more setInterval()
are created and the counter is deducted for more and more times, finally resulting in accelerating decrement.
Second attempt, utilizing useEffect hook
Ok, maybe we can solve the problem by just trigger the setInterval()
once in the life cycle of a component by using useEffect()
react hook.
function App() {
const [counter, setCounter] = React.useState(60);
// Second Attempts
React.useEffect(() => {
counter > 0 && setInterval(() => setCounter(counter - 1), 1000);
}, []);
return (
<div className="App">
<div>Countdown: {counter}</div>
</div>
);
}
useEffect
is a react hook which accepts parameters including a function to be triggered at a specific point of time and an array of dependencies.
- If the dependencies are not specified, the function is triggered every time any state inside of this component is updated.
- If the dependencies are specified, only when the particular dependant state is changed, the function is triggered.
- If the dependency array is empty, then the function is only triggered once when the component is initially rendered.
So in this way, surely setInterval()
can only be triggered once when the component is initially rendered.
Are we getting the correct result here?
Wrong again! The countdown mysteriously freezes after being decremented by 1. I thought setInterval()
should be running continuously? Why it is stopped? To find out what happened, let's add a console.log()
.
React.useEffect(() => {
counter > 0 &&
setInterval(() => {
console.log(counter);
setCounter(counter - 1);
}, 1000);
}, []);
Now the console prints out:
All the numbers printed out are 60, which means the counter itself has not been decreased at all. But setCounter()
definitely has run, then why isn't the counter
updated?
This counter
is indeed not decreased because the setCounter
hook essentially does not change the counter
within THIS function. The following illustration may make things clearer.
Because every time when the component is re-rendered, the App()
function is called again. Therefore, within the App()
scope, only in the first time, the useEffect()
is triggered and the setInterval()
is within the first time App()
scope with the property counter
always equal to 60.
In the global environment, there is only one setInterval()
instance which contiguously set the counter
to 59, causing new App()
calls always get the state counter
to be 59. That's why the counter seems to be freezed at 59. But in fact, it is not freezed, it is being reset all the time but the value is ALWAYS 59.
Third Attempts, useEffect with cancelling interval
To overcome the issue mentioned above, we need to trigger the setInterval()
in every single App()
call with different counter
value, just as illustrated below.
To achieve that, we need to do 2 things:
- Let
setInterval()
get triggered every time when component gets re-rendered Solution: add a dependency ofcounter
inuseEffect
hook so that every time when thecounter
changes, a newsetInterval()
is called. - Clear
setInterval()
in this scope to avoid duplicated countdown Solution: add a callback function inuseEffect
hook to clear the interval in current scope so that only onesetInterval()
instance is running in the global environment at the same time.
Thus, the final solution is
function App() {
const [counter, setCounter] = React.useState(60);
// Third Attempts
React.useEffect(() => {
const timer =
counter > 0 && setInterval(() => setCounter(counter - 1), 1000);
return () => clearInterval(timer);
}, [counter]);
return (
<div className="App">
<div>Countdown: {counter}</div>
</div>
);
}
And it looks correct!
Thank you for reading!!
Update on 9 Dec 2019
Thanks to @Laurent, he suggested me to use setTimeout()
to replace setInterval()
in the final solution, which I think it's a better idea! setTimeout()
only runs once, hence, we don't have to clear the setInterval()
in every useEffect()
change. Wonderful!
Top comments (18)
I think you just complicated the things unnecessarily, always remember this rule of thumb
This solution works, but it has a problem, the countdown never stops.
To make it stop at 0, we will make use of useRef hook, it will store the reference to the setInterval, whihc we can clear when the timer is 0.The complete solution would look like this.
codesandbox.io/s/reverent-bash-bxrnv
please let me know your thoughts on this.
Hi Arpan , i think if you pass Timer as dependency in useEffect, that will do the job simply.
you dont need to use useRef and 2nd useEffect.
let me know your thoughts.
React.useEffect(() => {
const TimerInt = timer >0 && setInterval(() => {
setCounter((time)=>time-1);
}, 1000);
return () => {
clearInterval(TimerInt)
}
}, [timer]);
hey this is a very nice implementation , but consider i want the timer to completely stop at 0 , and then we want the countdown again , if we change the value of timer then it won't do anything.
Any idea how we can overcome this
Your solution is more intuitive than mine. Nice one!
Thank you!
I had good success creating a timer by storing the current datetime when starting the timer, and then on every interval getting the new current datetime again and doing the math to find the difference. If any computation takes longer than it should - it doesn't matter. The date time is always valid
Hey Sean! Interesting thoughts! I tried your approach, and it also works!
Thanks! That's awesome
Nice work! Learned good stuff and folks' comments! <3 Thanks!
Will point out that for more comprehensive timers a major problem with setIntervals or setTimeouts is that they're unreliable when switching between tabs/phone locks. Usually a 1000ms lag but can be arbitrary.
Solutions I've seen so far to the inaccuracy issue will be based on Date objects, Performance interface, requestAnimationFrame etc
You sir are amazing! You saved me so much time at work with this valuable post!! I needed to build a countdown from a certain date in days hours minutes and seconds.
Thank you! Glad it helps!
hi @zhiyueyi , let me know your thoughts about this.
React.useEffect(() => {
const TimerInt = timer >0 && setInterval(() => {
setCounter((time)=>time-1);
}, 1000);
return () => {
clearInterval(TimerInt)
}
}, [timer]);
Cool, thank you! Only flaw is that if the user switches to a different tab, the timer pauses. Any thoughts on how to get around that, or is that just a limitation of how JavaScript runs in the browser?
Whats limitation?
If your component will unmount, you should lift your count state up (or make it global) to store the current count. Then when remount, init your count state with the previous count. It'll start counting at the previous position.
If you component will not unmount, just clear your current timeout when the tab lost focus. It'll pause. When it get focused again, set your timeout back.
I like the approach of the author, its simple and clean..
Hi!
If instead "setInterval" you use "setTimeout", your timer works perfectly in a simple code like your first try.
Thanks 😂!!! It's Helpful to me <3
realy like your post, it's really useful, thanks!!!!!!