Write a JavaScript Program to Pass Parameter to a setTimeout() Function

The setTimeout() function in JavaScript is used to execute a piece of code after a certain amount of time has passed.

It takes two arguments: a callback function and a delay time in milliseconds.

However, it’s also possible to pass additional parameters to the callback function using the setTimeout() function.

To pass parameters to a setTimeout() function, you can use an anonymous function that calls the original function with the desired parameters. Here’s an example:

function myFunction(param1, param2) {
  console.log(param1 + param2);

setTimeout(function() {
  myFunction("Hello, ", "World!");
}, 2000);

In the above example, we have a function called myFunction() that takes two parameters and logs their concatenation to the console.

We then pass an anonymous function to the setTimeout() function, which in turn calls myFunction() with the desired parameters after a delay of 2 seconds.

The anonymous function acts as a wrapper that allows us to pass parameters to the original function. We can pass as many parameters as we want by adding them to the myFunction() call inside the anonymous function.

In conclusion, passing parameters to a setTimeout() function is easy in JavaScript.

All you need to do is use an anonymous function as a wrapper and call the original function with the desired parameters inside it.

This allows you to execute a piece of code with a delay and pass any additional data it requires.