Pause execution for a specified number of milliseconds using async/await
Quick Answer
JavaScript has no built-in sleep, but you can create one by wrapping setTimeout in a Promise and awaiting it inside an async function.
1const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
2
3// Usage
4async function example() {
5 console.log('Start');
6 await sleep(2000);
7 console.log('After 2 seconds');
8}JavaScript does not have a built-in sleep function like other languages, but we can create one using Promises and setTimeout. This allows you to pause execution in async functions, which is useful for rate limiting, testing, or creating delays in animations.
No. The Promise-based implementation is non-blocking. The event loop continues to process other tasks while the timeout is pending.
Yes. Wrap setTimeout in a class that exposes a cancel method which calls clearTimeout and resolves the Promise early.
Node 22+ exposes timers/promises with setTimeout that returns a Promise, effectively a built-in sleep.
This free javascript code snippet for sleep function is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement sleep function quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.