Categories
JavaScript Answers

How to Pass Arguments to the JavaScript setTimeout Function’s Callback?

Spread the love

The setTimeout function lets us run JavaScript code after a delay in milliseconds.

In this article, we’ll look at how we can pass in arguments to the JavaScript setTimeout function.

Call setTimeout with More Argumemts

One way to pass arguments to the setTimeout function’s callback is to pass them in after the 2nd argument of setTimeout .

For instance, we can write:

setTimeout((greeting, name) => {  
  console.log(greeting, name)  
}, 1000, 'hello', 'jane')

We have a callback that takes the greeting and name parameters.

And we have the 'hello' and 'jane' arguments after the 2nd argument.

They’ll get passed into the callback in the same order.

So the console log should log hello jane .

Use the bind Method

The bind method lets us return a function with the arguments we want passed in.

So we can use the function returned by bind as the callback instead.

For instance, we can write:

const greet = (greeting, name) => {  
  console.log(greeting, name)  
}  
setTimeout(greet.bind(undefined, 'hello', 'jane'), 1000)

to call greet with the arguments that we pass into bind with setTimeout .

The 2nd and subsequent arguments of bind are passed into the greet function.

So we get the same result as before.

Call the Function in the Callback

Another way we can pass arguments into the setTimeout callback is to call the function we want in the callback.

For instance, we can write:

const greet = (greeting, name) => {  
  console.log(greeting, name)  
}  
setTimeout(() => {  
  greet('hello', 'jane')  
}, 1000)

Instead of trying to pass the greet function into setTimeout directly, we call greet in the callback with the arguments that we want instead.

This gives us the same results as before.

Conclusion

There’re several ways to pass in arguments to the setTimeout callback.

We can transform the callback with bind , or we can pass in the arguments directly to setTimeout .

Also, we can call the function we want in the callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to Pass Arguments to the JavaScript setTimeout Function’s Callback?”

Leave a Reply

Your email address will not be published. Required fields are marked *