How to Pass a Parameter to a setTimeout() Callback in JavaScript

JavaScript is one of the most popular programming languages in the world, and setTimeout() is a fundamental part of JavaScript’s timing functions.

This function allows developers to execute a piece of code after a specified amount of time has passed.

However, what if you want to pass a parameter to the callback function that is executed by setTimeout()?

This tutorial will show you how to do exactly that.


What is setTimeout()

setTimeout() is a JavaScript function that allows you to schedule a function to be executed after a specified amount of time.

The function takes two arguments: a callback function, and a time interval in milliseconds.

For example, the following code will execute the callback function “callbackFunction” after 2 seconds:

setTimeout(callbackFunction, 2000);

Passing a Parameter to the Callback Function

One of the most common use cases for setTimeout() is to pass a parameter to the callback function.

However, this can be tricky because setTimeout() expects the first argument to be a function, and not a value.

Fortunately, there is a simple solution to this problem.

You can use an anonymous function to pass the parameter to the callback function.

This anonymous function takes the parameter as an argument, and then executes the callback function with the parameter.

Here’s an example:

setTimeout(function() {
  callbackFunction(parameter);
}, 2000);

In this example, the anonymous function takes the parameter “parameter” and passes it to the callback function “callbackFunction”.

This allows you to pass the parameter to the callback function, even though setTimeout() only accepts functions as its first argument.

Passing Multiple Parameters

You can also pass multiple parameters to the callback function by passing an anonymous function that takes multiple arguments.

Here’s an example:

setTimeout(function(param1, param2) {
  callbackFunction(param1, param2);
}, 2000, param1, param2);

In this example, the anonymous function takes two parameters, “param1” and “param2”, and passes them to the callback function “callbackFunction”.

This allows you to pass multiple parameters to the callback function, even though setTimeout() only accepts functions as its first argument.


Conclusion

In this tutorial, we showed you how to pass a parameter to a setTimeout() callback function in JavaScript.

By using an anonymous function, you can pass parameters to the callback function, even though setTimeout() only accepts functions as its first argument.

Whether you’re a beginner or an experienced JavaScript developer, this technique will come in handy in your future projects.