| Tutorials | JavaScript |

How to Pass Parameters to setInterval in JavaScript?

The setInterval() function in JavaScript allows you to execute a function repeatedly at a defined time interval (in milliseconds).
Sometimes, it’s necessary to pass parameters to that function to customize its behavior.

In this tutorial, you’ll learn the most common ways to do it.


Basic Syntax of setInterval

setInterval(function, time, parameter1, parameter2, ...);
  • function: the function to execute.
  • time: the interval in milliseconds.
  • parameterX: optional values that can be passed to the function.

Passing Parameters Directly

You can pass parameters as extra arguments after the time:

function greet(name, age) {
  console.log(`Hello ${name}, you are ${age} years old.`);
}

setInterval(greet, 2000, "Carlos", 30);
// Every 2 seconds it will display: Hello Carlos, you are 30 years old.

Using an Arrow Function

You can also use an anonymous function or arrow function to control the parameters:

setInterval(() => {
  greet("Ana", 25);
}, 3000);

Using bind() to Fix Parameters

Another way is to use the bind() method:

function showMessage(message) {
  console.log(message);
}

setInterval(showMessage.bind(null, "Hello from bind!"), 4000);

  • You can pass parameters directly in setInterval().
  • You can also use arrow functions or bind() for more flexibility.
  • This technique is useful to run custom functions with dynamic data at time intervals.

Now you know how to pass parameters to setInterval in JavaScript and apply it in your projects.