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.
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