JavaScript can execute a function after a specified amount of time using setTimeout(). A wrapper function can also be created to make delayed execution reusable with different functions and arguments.
- Use setTimeout() to delay function execution.
- Pass function arguments using rest and spread syntax.
- A callback or wrapper function can make delayed execution reusable.
Approach 1: Using a Wrapper Function
Create a callAfter() function that accepts the delay, callback function, and its arguments. The callback is executed after the specified delay using setTimeout().
function callAfter(delay, callback, ...params) {
setTimeout(() => {
callback(...params);
}, delay);
}
function add(a, b) {
console.log("The sum is:", a + b);
}
callAfter(2000, add, 4, 7);
Output
The sum is: 11
The function executes after 2 seconds.
Syntax:
callAfter(delay, callback, ...parameters);Approach 2: Using an Anonymous Function
An anonymous function can be passed as the callback when the function needs to be called with specific arguments after the delay.
function callAfter(delay, callback) {
setTimeout(callback, delay);
}
function add(a, b) {
console.log("The sum is:", a + b);
}
callAfter(2000, () => {
add(4, 7);
});
Output
The sum is: 11
- The arrow function delays the call to add().
- add(4, 7) executes only after the specified delay.
- This approach is useful when additional logic is required before calling the function.
Approach 3: Using Function.prototype
A custom callAfter() method can be added to Function.prototype, allowing functions to call the method directly.
Function.prototype.callAfter =
function(delay, ...params) {
setTimeout(() => this(...params), delay);
};
function add(a, b) {
alert("The sum is : " + (a + b));
}
add.callAfter(2000, 4, 7);
Syntax:
functionName.callAfter(delay, param1, param2, ...);Note: The first approach is generally preferable because modifying Function.prototype can affect all functions globally and may lead to naming conflicts.