Build a Countdown Timer with React.JS

Rohit Kashyap
2 min readSep 24, 2019
Photo by NeONBRAND on Unsplash

Recently, I had to implement an OTP sending functionality into our application. This came in handy when the SMS-service we used did not respond. As many applications do, we decided to add this feature.

Since this is just a button, it’s crucial to make sure that the user is not requesting for an OTP a thousand by repeatedly clicking on the same button. This is where a countdown timer might come in, we can allow the user to request an OTP once 30 seconds have passed since their first OTP.

Here, we will go through the process of building a relatively simple 30-second timer. Of course, you can implement it further to make it work with minutes and hours.

setInterval is an inbuilt javascript function that allows you to run a piece of code or execute a function every x milliseconds. Combining with this our react component, we can achieve what we want.

We have a button to initiate the counter. Notice the line:

this.id = setInterval(this.initiate, 1000);

With this, we are getting the id of the setInterval call, setInterval returns a unique id. Using this id, we can stop the interval from further executing. The same is happening here. As soon as the counter hits 0 seconds, we stop the timer to further execute.

Here is a sandbox link for you guys to check out:

Hope this helped you, this is my first medium article. Go easy on me :)

--

--

Rohit Kashyap

Engineer at Falabella India | JavaScript Enthusiast