Promises 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:

Output

How to Delay a Function Call in JavaScript ?

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:

Table of Content

  • Using setTimeout()
  • setInterval()
  • Promises with setTimeout()
  • Async/Await with setTimeout()

Similar Reads

Using setTimeout()

The setTimeout() method schedules a function to be executed after a specified delay in milliseconds....

setInterval()

Similar to setTimeout(), setInterval() repeatedly calls a function with a fixed time delay between each call....

Promises with setTimeout()

We can create a Promise and resolve it after a certain delay using setTimeout(). This allows for better handling of asynchronous operations....

Async/Await with setTimeout()

Using async/await syntax with setTimeout() allows for writing asynchronous code in a synchronous-like manner, improving code readability and maintainability....

Contact Us