0
0
JavascriptHow-ToBeginner · 3 min read

How to Sleep in JavaScript: Simple Delay Techniques

In JavaScript, you can create a sleep or delay effect by using async functions combined with await and Promises. This pauses the code execution for a set time without blocking the whole program.
📐

Syntax

To sleep in JavaScript, define a function that returns a Promise which resolves after a delay using setTimeout. Then use await inside an async function to pause execution until the promise resolves.

  • sleep(ms): Function that returns a promise resolving after ms milliseconds.
  • await sleep(ms): Pauses the async function for ms milliseconds.
javascript
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function example() {
  console.log('Start');
  await sleep(1000); // pause for 1 second
  console.log('End after 1 second');
}
💻

Example

This example shows how to pause code execution for 2 seconds using sleep inside an async function. The console logs before and after the pause demonstrate the delay.

javascript
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demoSleep() {
  console.log('Waiting starts');
  await sleep(2000); // wait for 2 seconds
  console.log('2 seconds passed');
}

demoSleep();
Output
Waiting starts 2 seconds passed
⚠️

Common Pitfalls

One common mistake is trying to use sleep in a non-async function or without await, which will not pause execution as expected. Another is using blocking loops like while to simulate sleep, which freezes the whole program and is bad practice.

Correct usage requires an async function and await keyword.

javascript
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// Wrong: no async/await, so no pause
function wrongSleep() {
  sleep(1000);
  console.log('This runs immediately');
}

// Right: async function with await
async function rightSleep() {
  await sleep(1000);
  console.log('This runs after 1 second');
}
📊

Quick Reference

Use this quick guide to remember how to sleep in JavaScript:

ConceptUsageNotes
Sleep functionfunction sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }Creates a delay promise
Pause executionawait sleep(1000);Use inside async functions only
Async functionasync function myFunc() { await sleep(1000); }Required to use await
Avoid blockingNo while loops for sleepBlocks event loop, freezes app

Key Takeaways

Use async functions with await and Promises to create sleep delays in JavaScript.
Never use blocking loops to simulate sleep as it freezes the program.
The sleep function returns a Promise that resolves after a set timeout.
Always call sleep with await inside an async function to pause execution properly.