JavaScript setInterval() method explained

Learn how setInterval() method works here

Posted on March 17, 2021

The JavaScript setInterval() method is a method from the DOM Window object that allows you to run a specific function at a defined interval.

For example, the following fnLog() function will be executed every 1 second:

let timer = setInterval(fnLog, 1000);

function fnLog() {
  console.log("Function fnLog executed");

The setInterval() method requires two parameters:

  • The function to execute
  • The number interval, specifying how often you want to execute the function. The number interval is in milliseconds, so 1000 equals to 1 second.

The setInterval() method also accepts extra parameters that will be passed to the function that you will execute:

setInterval(fnLog, 1000, param1, param2, ...);

For example, the “Hello World” parameter will be passed to the fnLog() function:

// pass "Hello World" to fnLog
let timer = setInterval(fnLog, 1000, "Hello World");

function fnLog(str) {
  console.log(str); //"Hello World"

The setInterval() method will return an id that you can use to stop the intervals from executing repeatedly.

To stop the intervals, use the clearInterval() method:


Both the browser and Node.js has the setInterval() method implemented, so you can use the method on both environments.

Related articles:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more