How to use Promises and async/await In Javascript

You can also create a delay using Promises and the async/await syntax. This approach is useful when you want to use delay within an asynchronous function.

Example: In this example, the delay function returns a Promise that resolves after a specified number of milliseconds. The myGeeks uses await to pause its execution until the delay is completed.

Javascript
function delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function myGeeks() {
    console.log("Waiting 2 seconds...");
    await delay(2000);
    console.log("Function executed after 2 seconds");
}

myGeeks();

Output

Waiting 2 seconds...
VM141:8 Function executed after 2 seconds

How to Delay a JavaScript Function Call using JavaScript ?

When we want to call a function after a described amount of time, we use a delay function in JavaScript.

There are several ways to delay the execution of a function. This can be useful for various purposes, such as creating animations, implementing debounce in search inputs, or simply delaying an action until a certain condition is met.

Table of Content

  • Using setTimeout() Method
  • Using Promises and async/await
  • Using setInterval() for Repeated Delays
  • Canceling a Delay

Similar Reads

Using setTimeout() Method

The most common way to delay a function in JavaScript is by using the setTimeout() function. This function allows you to specify a delay (in milliseconds) after which a function will be executed....

Using Promises and async/await

You can also create a delay using Promises and the async/await syntax. This approach is useful when you want to use delay within an asynchronous function....

Using setInterval() for Repeated Delays

If you need to repeatedly delay a function at fixed intervals, you can use setInterval() method....

Canceling a Delay

You can cancel a delay created with setTimeout() or setInterval() using clearTimeout() and clearInterval() respectively....