The power of setInterval() and clearInterval()

Dong Xia
2 min readMay 30, 2021

--

DOM Window

Photo by Ocean Ng on Unsplash

The HTML DOM has a number of Window methods available. Some of the most popular are console.log(), localStorage, and alert().

We are going to focus about setInterval() and clearInterval(), a set of valuable methods that are used in many application.

setInterval() Method

The setInterval method is a method that calls a function or evaluates an expression at specific time interval. The first parameter is the function that wants to be called or evaluated. The second parameter is the time interval from one call to the next. 1000 is equal to 1 second.

setInterval(function, milliseconds)

The most popular usage is setting a timer or clock. A clock ticks every seconds so the function needs to be called again and again, to consistently get the current time.

function clock() {
return new Date().toLocaleTimeString()
}
setInterval(clock, 1000);

clearInterval() Method

The clearInterval method is used in conjunction with the setInterval method. If there is a start, there should be a end as well.

The clearInterval parameter is the setInterval method itself. Be careful on how the setInterval is passed in. One might think clearInterval( setInterval() ), however this way is wrong. Rather than passing setInterval() directly, you MUST create a variable for setInterval() and then pass the variable into clearInterval.

Wrong
clearInterval( setInterval(function, 1000) )

Correct
const VAR = setInterval(function(), 1000)
clearInterval(VAR)

Why create the extra step?

Remember, pass by value (PBV) and pass by reference (PBR).

Pass by value is like making another copy. Copy1 and copy2 are the same but their memory and space location are in different places. If you do something to copy1, copy2 isn’t affect by the changes in copy1.

Pass by reference is not creating a copy but rather pointing to its original source or memory location. If you modify the original source, the variables that are using the original reference, their values will also change accordingly.

You can think of it like (PBV) immutable vs (PBR) mutable.

This is PBV, there are 2 different copy of the setInterval.
setInterval(function, 1000)
clearInterval( setInterval(function, 1000) )

This is PBR, clearInterval is referring back to the setInterval
const VAR = setInterval(function(), 1000)
clearInterval(VAR)

Run one time

setTimeout() and clearTimeout() are very similar to setInterval() and clearInterval(). The only different is that setTimeout only runs once.

A mini project

I was able to create a play game and pause game, using the setInterval() and clearInterval().

https://dong-yi-xia.github.io/snake_app/

--

--

Dong Xia
Dong Xia

Written by Dong Xia

Copy and Paste what’s on my mind. Perfect.

No responses yet