DEV Community

CodingWith-Adam
CodingWith-Adam

Posted on

1 1

How to make a sleep function in JavaScript with async await

In this video I’m going to show you how you can add a sleep function in JavaScript. Languages like .net, python and java have a method called sleep. This allows a method to pause and wait for a certain amount of time and then continue execution of its code. JavaScript does provide a setTimeout method where you can pass a function to execute after a certain amount of time. However with the addition of async and await in javascript we can write this solution in a more elegant way.

This is the solution used in the video:

async function sleep(seconds) {
return new Promise((resolve) =>setTimeout(resolve, seconds * 1000));
}

Top comments (1)

Collapse
 
bhawana_kumari_98d7a967af profile image
Bhawana kumari

Thanks for sharing! By the way, I came across this discussion on implementing a "sleep" function in JavaScript that might be helpful: community.lambdatest.com/t/javascr...

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay