I’m wondering if there is a JavaScript sleep function available that can pause execution for a specific amount of time, similar to sleep functions in other programming languages. How can I implement this in JavaScript?
Been writing JS for a while now, and when working with async workflows, this is my go-to:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// usage
await sleep(1000); // pauses for 1 second
Honestly, this is the cleanest and most readable way to use a javascript sleep function in modern code. Works perfectly in async
functions and keeps the flow super natural. Makes pauses feel like a first-class citizen in your logic.
Totally agree with @dimplesaini.230 ! But if you’re dealing with older codebases or environments without async/await, here’s a solid fallback I’ve leaned on quite a few times:
function sleep(ms, callback) {
setTimeout(callback, ms);
}
// usage
sleep(1000, () => console.log("Slept for 1 sec"));
This is kind of the OG javascript sleep function approach. Not as sleek as Promises, but still effective. Just keep in mind it can get messy if you chain too many callbacks—hello callback hell!
Ha, both of those are solid. But just to throw it out there for completeness (and a little cautionary tale from my early days):
function sleep(ms) {
const end = Date.now() + ms;
while (Date.now() < end);
}
This version of a javascript sleep function literally halts everything—no clicks, no animations, nothing. It’s synchronous and blocks the main thread. Technically it works, but you’ll freeze your whole UI. Great for learning what not to do in production