How to Use setInterval() and Build a Basic Stopwatch Using React

Claire DeBoer
2 min readApr 28, 2021

I just learned how to use the setInterval() method by making a simple stopwatch app using React. Besides the classic stopwatch use case, another way you might use this method is in something called polling where fetch calls are sent repeatedly at intervals.

Let me break down what I learned.

Basic Syntax

The basic idea is that the setInterval() method calls a function at specified intervals and will continue to do so until clearInterval() is called or the window is closed. The first required parameter is the function you want to be executed at every interval and the second, also required, parameter is the amount of time in milliseconds that you want to pass between function calls. The basic syntax is :

setInterval(function, milliseconds)setInterval(() => {alert(‘Bonjour’);}, 3000);

The above method will send a pop up alert saying ‘Bonjour’ every 3 seconds. Remember, 1 second is 1000 milliseconds.

Stopping the Function Using clearInterval()

As I mentioned above, the setInterval() method will fire until clearInterval() is called. setInterval() returns a variable called interval ID which is in turn used in clearInterval() like so.

intervalId = setInterval(function, milliseconds);clearInterval(intervalId);

Keep in mind, the sister method of setInterval() is setTimeout(). Where setInterval() repeats a function multiple times at specified intervals, setTimeout() simply delays the execution of a function one time.

Here is my React code for building a stopwatch. The end result is a simple stopwatch that looks like this.

The above code uses setInterval() three times within the handleStart() function to set centiseconds, seconds, and minutes in state. Then the handleStop() function sets the state for all three to 0 and passes the returned interval Id (centiSpanse, secSpanse, and minSpanse in this case) into clearInterval() three times to dismount each. Hope this helps! Don’t be late!

--

--