Sitemap

Delays in JavaScript: How to Make Your Code Wait the Right Way

4 min readNov 13, 2025

--

Press enter or click to view image in full size

Have you ever wanted your JavaScript code to “pause” for a moment — maybe to wait between API requests, show a loading animation, or delay an action until something else happens?

In most programming languages, you’d use a sleep() function for that. But JavaScript doesn’t have one. That’s because it’s asynchronous — it never stops running while waiting for something to finish.

Still, there are simple ways to make your JavaScript code wait without blocking everything else. In this article, you’ll learn exactly how to add delays in both the browser and Node.js, along with some practical examples where delays make your code cleaner and your apps feel smoother.

1. The Simple Way: Using setTimeout()

The easiest and oldest way to add a delay in JavaScript is with the setTimeout() function. It runs code after a specified amount of time (in milliseconds).

console.log("Start");

setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);

console.log("End");

What happens:

  1. “Start” appears immediately.
  2. JavaScript schedules the delayed code to run after 2 seconds.
  3. “End” prints right away — the rest of the program keeps running.

So setTimeout() doesn’t stop the program. It simply tells JavaScript to do something later.

Example use case:
Show a confirmation message 2 seconds after a user submits a form, to make the interaction feel smoother.

2. A Cleaner Way: Creating a Reusable Delay Function

When you need multiple delays or want cleaner async code, you can wrap setTimeout() inside a Promise. This gives you a simple, reusable function.

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

console.log("Wait...");

delay(2000).then(() => {
console.log("2 seconds later");
});

This delay() function can now be used anywhere in your code — in both browsers and Node.js — without cluttering your logic.

Example use case:
Simulate loading time in your app. For instance, show a “Loading…” message for a couple of seconds before displaying results.

3. The Modern Approach: Using async and await

Modern JavaScript (ES2017 and later) introduced async/await, which makes asynchronous code look more natural and easier to read.

Here’s how to add a delay using this syntax:

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

async function runExample() {
console.log("Starting...");
await delay(3000);
console.log("3 seconds later...");
}

runExample();

The await keyword tells JavaScript to pause inside that async function until the delay finishes — without freezing the whole program.

Example use case:
When calling an external API, you can pause between requests to avoid rate limits or reduce server load.

4. Node.js Has Its Own Way: timers/promises

If you’re using Node.js 15 or later, there’s an even simpler built-in solution: the timers/promises module.

import { setTimeout as delay } from 'timers/promises';

async function main() {
console.log("Waiting...");
await delay(2000);
console.log("Done waiting.");
}
main();

This method doesn’t require defining your own delay() function — it’s part of the Node.js standard library.

Get Sangwin Gawande’s stories in your inbox

Join Medium for free to get updates from this writer.

Example use case:
Pause between database operations or retry attempts when connecting to external services.

5. What Not to Do: Blocking Delays

Some developers try to create a manual delay using a loop, like this:

const start = Date.now();
while (Date.now() - start < 3000) {
// Busy waiting
}

Although it looks like a delay, it’s actually blocking the program. While this loop runs, JavaScript can’t do anything else — not even respond to clicks or API calls.

In browsers, this can make your page freeze. In Node.js, it can block other requests. Always use non-blocking approaches like Promises or setTimeout() instead.

6. Practical Use Cases for Delays

Here are a few real-world examples where adding a delay is not just useful, but often necessary:

a) Throttling or Rate Limiting

APIs often restrict how many requests you can make per second. Adding a delay between requests helps you stay within those limits.

for (const id of [1, 2, 3]) {
await fetch(`https://api.example.com/data/${id}`);
await delay(1000); // wait 1 second between calls
}

b) Improving User Experience

Sometimes, a short delay can make transitions feel smoother. For instance, wait half a second before showing a success message after saving data, so users see a clear flow of actions.

c) Retrying Failed Requests

If a network call fails, you can retry it after a short pause.

async function fetchDataWithRetry(url) {
for (let attempt = 1; attempt <= 3; attempt++) {
try {
return await fetch(url);
} catch {
console.log(`Retrying in 2 seconds... (Attempt ${attempt})`);
await delay(2000);
}
}
}

This pattern is common in APIs, web crawlers, and backend services.

While JavaScript doesn’t have a built-in sleep() function, adding a delay is simple once you understand asynchronous code.

Delays help control timing, improve user experience, and prevent issues like API rate-limit errors, all without blocking your main program.

Conclusion

JavaScript’s event-driven design means it never truly stops running. Instead of trying to “pause” everything, the goal is to schedule when things happen.

By using modern async tools like Promises and await, you can control timing elegantly while keeping your code responsive and easy to follow.

Once you get comfortable with this pattern, adding delays — or even building more complex timing logic — will feel natural.

About the Author

Written by Sangwin Gawande (https://sangw.in)

A web developer and JavaScript enthusiast who enjoys writing simple, practical guides for modern coding challenges.

If you found this article helpful, follow me for more posts about JavaScript, Node.js, and web development best practices.

--

--

Sangwin Gawande
Sangwin Gawande

Work with me? Sure, Let's catch up. Website : https://sangw.in Email : imsangwin@gmail.com