You can pass arguments to the callback function in setTimeout() by using anonymous functions or arrow functions.
1. Using an anonymous function (or arrow function):
You can pass arguments by wrapping your callback in an anonymous function or an arrow function, which then calls the actual callback with the desired arguments.
Example:
function greet(name) {
console.log('Hello, ' + name);
}
// Using setTimeout with an anonymous function
setTimeout(function() {
greet('Alice');
}, 1000);
// Or using an arrow function
setTimeout(() => greet('Bob'), 2000);
2. Using bind() method:
You can also use the bind() method to pre-assign arguments to your callback function before passing it to setTimeout().
Example:
function greet(name) {
console.log('Hello, ' + name);
}
setTimeout(greet.bind(null, 'Charlie'), 3000);