Photo by Brad Neathery on Unsplash

The Basics of Timer Functions in JavaScript

setTimeout and setInterval explained

Jonathan Yee
Jul 11 · 2 min read

People who use the internet encounter timers everyday without even knowing.

Timers are functions that delay or repeat the execution of another function.

They are not native to JavaScript, rather are managed by Browsers (the Window interface)and in Node.js (the global object).

The setTimeout function is used to delay the execution of another function.

setTimeout requires two parameters: a callback function that will be executed after the delay and the length of the delay in milliseconds (1 second = 1000 milliseconds).

In the example above, printHelloWorld() is executed after 2 seconds, logging “Hello World” to the console.

As well, any additional arguments passed to setTimeout will be subsequently passed to the callback function.

In the above example, printSomething() is executed after 1 second, logging “Hello World” in the console.

The setInterval function is used to repeat the execution of a function for every determined length of time.

As before, setInterval requires two arguments: a callback function that will be executed and the length of time in milliseconds the function will repeat.

In the above example, the local time will be printed to the console every second forever.

To cancel a repeating timer, you would use the clearInterval function.

Note: the code above is possible because of hoisting. How exciting!

In the above example, printTime() is executed every second for ten seconds.

To review, timers are used to delay or repeat the executions of other functions. You may encounter timers being used everyday, from Pomodoro timers, meditation countdowns, to features as unnoticeable as background photos changing every couple seconds. Knowing how these functions work will enable you to better tackle the demands of today’s industry.