How to Delay a Function Call in JavaScript ?
Last Updated :
26 Mar, 2024
Delaying a JavaScript function call involves executing a function after a certain amount of time has passed. This is commonly used in scenarios where you want to postpone the execution of a function, such as in animations, event handling, or asynchronous operations.
Below are the methods to delay a JavaScript function call:
Using setTimeout()
The setTimeout() method schedules a function to be executed after a specified delay in milliseconds.
Syntax:
setTimeout(function, delay, arg1, arg2, ...);
Example: Printing the output after 2 seconds using setTimeout().
JavaScript
setTimeout(() => {
console.log('Function called after 2000 milliseconds');
}, 2000);
Output:
OutputsetInterval()
Similar to setTimeout(), setInterval() repeatedly calls a function with a fixed time delay between each call.
Syntax:
setInterval(function, delay, arg1, arg2, ...);
Example: Printing the each output after interval of 1 second using setTimeout().
JavaScript
let count = 0;
const intervalID = setInterval(() => {
console.log('Function called every 1000 milliseconds');
count++;
if (count === 3) {
clearInterval(intervalID);
}
}, 1000);
Output:
OutputPromises with setTimeout()
We can create a Promise and resolve it after a certain delay using setTimeout(). This allows for better handling of asynchronous operations.
Syntax:
const delayedFunction = (delay) => new Promise(resolve => setTimeout(resolve, delay));
Example: Printing the output at a delay of 3 seconds using Promises with setTimeout().
JavaScript
const delayedFunction = (delay) => new Promise(resolve => setTimeout(() => {
console.log('Function called after ' + delay + ' milliseconds');
resolve();
}, delay));
delayedFunction(3000);
Output:
OutputAsync/Await with setTimeout()
Using async/await syntax with setTimeout() allows for writing asynchronous code in a synchronous-like manner, improving code readability and maintainability.
Syntax:
async function delayedFunction(delay) {
await new Promise(resolve => setTimeout(resolve, delay));
// Your code to be executed after delay
}
Example: Printing the output at a delay of 4 seconds using Promises with setTimeout().
JavaScript
async function delayedFunction(delay) {
await new Promise(resolve => setTimeout(resolve, delay));
console.log('Function called after ' + delay + ' milliseconds');
}
delayedFunction(4000);
Output:
delayed function call using async/await along with setTimeout function
Similar Reads
How to Delay a JavaScript Function Call using JavaScript ? Delaying a JavaScript function call involves postponing its execution for a specified time using methods like setTimeout(). This technique is useful for timed actions, animations, or asynchronous tasks, enabling smoother user experiences and better control over when certain operations run.There are
3 min read
How To Create a Delay Function in ReactJS ? Delay functions in programming allow for pausing code execution, giving deveÂlopers precise control over timing. These functions are essential for tasks such as content display, animations, synchronization, and managing asynchronous operations. In this article, we will discuss how can we create a d
3 min read
How to Create a Custom Callback in JavaScript? A callback is a function that executes after another function has been completed in JavaScript. As an event-driven language, JavaScript does not pause for a function to finish before moving on to the next task. Callbacks enable the execution of a function only after the completion of another, making
3 min read
How to create an Asynchronous function in Javascript? JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title
6 min read
How to chain asynchronous functions in JavaScript ? JavaScript is a single-threaded, asynchronous programming language. Thus, some time-consuming operations like I/O, accessing the database, network calls, etc. are performed asynchronously so that it does not interrupt things in the only JS thread. This can be done by asynchronous code like promises
2 min read
How to add a delay in a JavaScript loop? JavaScript doesn't offer any wait command to add a delay to the loops but we can do so using setTimeout method. This method executes a function, after waiting a specified number of milliseconds. Below given example illustrates how to add a delay to various loops: For loop: JavaScript for (let i=0; i
3 min read
How to call a function repeatedly every 5 seconds in JavaScript ? In JavaScript, the setInterval() method allows you to repeatedly execute a function or evaluate an expression at specified intervals. This method is particularly useful for performing periodic tasks like updating a user interface or making repeated API calls.Syntax:Â setInterval(function, millisecond
2 min read
JavaScript Call a function after a fixed time In order to run a function multiple times after a fixed amount of time, we are using few functions. JavaScript setInterval() MethodThis method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed. Synta
3 min read
How to Set Time Delay in JavaScript? Delaying the execution of code is a fundamental technique that is commonly used in JavaScript for tasks like animations, API polling, or managing time intervals between actions. JavaScript provides several built-in methods to set time delays: setTimeout() and setInterval(). We can set time delay in
2 min read
Debouncing in JavaScript In JavaScript, debouncing is a technique used to ensure that a function is not called too frequently. It is commonly used in scenarios where events are triggered rapidly, such as typing in an input field or resizing a window. Without debouncing, functions might be executed many times in quick succes
6 min read