JavaScript setInterval() method explained

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:

clearInterval(timer);

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

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.