How to Pass a Parameter to a setTimeout() Callback

The setTimeout function executes code after a specified amount of time but can only handle constant parameters.

You can pass arguments to the function using the bind() method:

function valueLog(value) {
  console.log('j = ' + value);
}
// logs "j = 0", "j = 1", "j = 2", "j = 3", "j = 4" with 1 second delays between them
for (let j = 0; j < 5; j++) {
  setTimeout(valueLog.bind(this, j), j * 1000);
}

The setTimeout() Method

The setTimeout() method calls a function and evaluates an expression after a given number of milliseconds. The function is only executed once. To repeat execution, use the setInterval() method. The returned value timeoutID is a positive integer that identifies the timer which is created by the call to the setTimeout() method. The value can be passed to clearTimeout() to prevent the function from executing.

The bind() Method

The bind() method creates a new function which, when called, has its this keyword set to the provided value, with a specified sequence of arguments preceding any provided when the new function is invoked.

Do you find this helpful?

Related articles