Typically, the point of a JavaScript async function is to not block execution but occasionally I do want to introduce a delay in an async function (e.g. as part of a delay before retrying a remote call).
This line inside an async function will introduce a delay of 10 seconds (10000 ms).
await new Promise((res) => setTimeout(res, 10000)); // Delay 10 seconds.
Example Sleep Inside Async Function
const myFunction = async () => {
console.log('Before sleep');
// Delay 10 seconds.
await new Promise((res) => setTimeout(res, 10000));
console.log('After sleep');
};
myFunction();
Leave a Reply