How to Use Sleep () in JavaScript

An Introduction: setTimeout For Sleep in JavaScript

Being a web developer, at times you need to log a few messages to the console of your framework loop, carrying a delay of some seconds between each other. While other programming languages have their built-in sleep () feature to control the execution of code, there is no such functionality of sleep in JavaScript. Since it is designed to be non-blocking, the traditional “sleep” function here can freeze the entire window of the browser and also the user interface. Therefore, you need to use the next best possible option, i.e., setTimeout().

However, this methodology doesn’t go as regular code. You might have also tried executing it earlier at some point in JavaScript but couldn’t pull it off because it requires a different approach. In simple language, it is a timer to pause or delay the execution of a code for a given timeframe. In this blog, we will understand various approaches for developers to use the JavaScript sleep () function.

Why is Delay Required in JavaScript?

Before proceeding with the techniques of using sleep in JavaScript, it is crucial to understand the role of delay in the execution:

  • Asynchronous Operations: Handling background operations like API data fetching and implementing features like debouncing and throttling requires delays in the execution.
  • Animations & Transitions: Integrating accurate animation styles and transitions often needs time. Each frame of implementing animations requires delay and pause in JavaScript.
  • Third-Party Script Loading: Delaying the loading and executing third-party scripts of analytics, advertisements, and social media widgets requires time before execution.

Use setTimeout for Sleep in JavaScript

setTimeout is one of the most used methods to schedule the execution of a code function after a delay in JavaScript. It allows you to execute code after the stated pause or delay, especially in asynchronous operations, where the code following the setTimeout() call will continue to execute while the timer runs in the background.

setTimeout(() => { 
    // Code to be executed after the delay 
}, 1000); // Delay of 1000 milliseconds (1 second)
 

While most developers use setTimeout to defer a specified delay of milliseconds in processing a piece of code, there are also other uses that are listed below:

Delaying Execution:

The most common application is to add a wait before running some code. This can be applied to:

  • Showing messages or tooltips with some delay.
  • Adding “sleep” or “wait” support in a non-blocking way.
  • Creating animations or transitions without instantaneous initiation.

Asynchronous Operations and UI Updates:

  • Deferring heavy calculations: setTimeout(…, 0) can be used to delay computationally heavy work until the browser has had a chance to update the current UI, avoiding UI freezes. This is essentially bumping the task to the end of the event queue.
  • Managing race conditions: When the loading or initialization time of the DOM elements overlaps with the interference of your code, setTimeout() can delay it slightly so that the browser finishes its work first.
  • Mocking asynchronous calls: For development or testing purposes, setTimeout() can be used to mock network behavior or other asynchronous functions.

Implementing Retries and Backoff Strategies:

When a network request or other operation fails, setTimeout() can be used to implement a retry mechanism with increasing delays (exponential backoff) to avoid overwhelming the server.

If a network request or any other operation is unsuccessful, setTimeout( ) can be utilized to introduce a retry feature with interval growth (exponential backoff) so the server will not get flooded.

Creating One-Time Timers:

Contrary to setInterval(), which executes the same function repeatedly, setTimeout() is employed for activities that must be carried out only after the said time. A sound playing after a sports event or the display of a welcome pop-up after a user arrives on a page are illustrations of this.

General Syntax for setTimeout

The general structure of the setTimeout() method in JavaScript is as follows:

let timeoutID = setTimeout(functionToExecute, delayInMilliseconds, [arg1, arg2, …]);

In addition, there is another syntax of the JavaScript setTimeout() method as setTimeout(function, delay, param1, param2, …), which executes a function or a block of code once after a specified delay. Either of the codes can be used based on the circumstances.

Parameters

  • function: The first required parameter is the function to be executed after the timer expires. It can be a name, a sign, or an anonymous function.
  • delay: This is an optional integer to specify the delay of time, in milliseconds (1000 milliseconds = 1 second), before the function is executed. If omitted, the default value is 0.
  • param1, param2, …: Optional additional parameters to pass to the function when it is executed.

Example usage:

Using a named function

This method is useful for code readability and for reusing the function elsewhere.

function greet() {
console.log(“Welcome!”);
}
setTimeout(greet, 1000); // The ‘greet’ function is executed after 1 second
Using an anonymous function

This common approach defines a function directly within the setTimeout call.

setTimeout(function() {
console.log(“This message appears after 2 seconds.“);
}, 2000);

Benefits of setTimeout:

  • Works similar to sleep ()
  • Set scheduled delays
  • Execute code after delaying

Limitations of setTimeout:

  • Imprecise execution timing of the function
  • Minimum delay for setTimeout

Highlight: setTimeout is not a core feature of JavaScript or ECMAScript. It exists in the window object of a browser environment.

How to use “sleep” in JavaScript

Since there is no built-in sleep() function, there are several other ways to execute the same, starting with Async/Await.

Using Async/Await Function in JavaScript for Delay

You can implement the sleep () in JavaScript by using function of async and await. It is a modern approach. Create a sleep function by combining setTimeout() with an async/await pattern in the following manner.

Define a sleep function that returns a Promise. The promise will resolve after a specified number of milliseconds using setTimeout().

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

Use await to pause execution inside an async function.

async function delayedGreeting() {
console.log(‘Welcome‘);
await sleep(2000); // Pauses for 2 seconds
console.log(‘World!‘);
}

delayedGreeting();
// Output:
// Welcome
// (2-second delay)
// World!

The code snippet: Await sleep(2000) pauses the execution for 2 seconds. While await allows a promise to be settled. This makes the execution synchronous.

Benefits of Async/Await:

  • Make code flow synchronous
  • Makes debugging easier
  • Integrate easily with JavaScript syntax

Limitations of Async/Await:

  • Await delays the processing of the async function till the settlement of the promise
  • Doesn’t block execution, but can pause it

Using One-line Sleep function in JavaScript

One-line sleep function can be used in situations where there is a requirement of quick one-time delay. For instance:

// Define the one-line sleep function
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

// Example usage within an async function
async function demonstrateSleep() {
console.log(‘Start‘);
await sleep(2000); // Pause for 2 seconds (2000 milliseconds)
console.log(‘End‘);
}

demonstrateSleep();

Explanation:

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));:

  • This defines an arrow function sleep that takes ms (milliseconds) as an argument.
  • It returns a new Promise.
  • The Promise’s executor function receives a resolve function.
  • Inside the executor, setTimeout(resolve, ms) is called. This schedules the resolve function of the Promise to be called after ms milliseconds.
  • Once resolve is called, the Promise is fulfilled.

await sleep(2000);:

  • This line must be used inside an async function.
  • The await keyword pauses the execution of the async function until the Promise returned by sleep(2000) is resolved (i.e., after 2 seconds).
  • Once the Promise resolves, the async function resumes execution from that point.

This function is used for a swift delay in processing code. Mainly, it is used in inline delays without implementing in-depth or detailed functions.

Using Promises in JavaScript

Promises in JavaScript introduce a delay in JavaScript with clear code and comprehensibility. It is used for complicated workflows and testing.

Creating a Promise

A Promise is created using the Promise constructor, which takes an executor to function as an argument. The executor function receives two arguments: resolve and reject, both of which are functions.

const myPromise = new Promise((resolve, reject) => {
// Simulate an asynchronous operation
setTimeout(() => {
const success = true; // Or false for rejection
if (success) {
resolve(“Operation completed successfully!“);
} else {
reject(“Operation failed!“);
}
}, 2000);
});

Consuming a Promise

Promises are consumed using the .then(), .catch(), and .finally() methods.

  • .then(onFulfilled, onRejected): This method is used to handle the fulfilled (resolved) and rejected states of a Promise.
  • onFulfilled: A callback function executed when the Promise is resolved. It receives the resolved value as an argument.
  • onRejected: An optional callback function executed when the Promise is rejected. It receives the rejection reason (error) as an argument.
myPromise.then(
(result) => {
console.log(“Success:”, result); // Output: Success: Operation completed successfully!
},
(error) => {
console.error(“Error:”, error); // Output: Error: Operation failed!
}
);

.catch(onRejected): This is a shorthand for .then(null, onRejected) and is specifically used for handling rejections (errors).

myPromise.catch((error) => {
console.error(“Error:”, error); // Output: Error: Operation failed! 
}); 

.finally(onFinally): This method executes a callback function regardless of whether the Promise was fulfilled or rejected. It’s useful for cleanup operations.

myPromise.finally(() => { 
     console.log(Promise settled (either fulfilled or rejected).); 
   }); 

Chaining Promises

Promises can be chained together to perform sequential asynchronous operations. Each .then() or .catch() method returns a new Promise, allowing for further chaining.

 fetch(“/api/data”
.then((response) => response.json()) 
.then((data) => {
console.log(“Fetched data:”, data);
return processData(data); // Returns a new Promise
})
.then((processedResult) => {
console.log(“Processed result:”, processedResult);
})
.catch((error) => {
console.error(“Error in chain:”, error);
}); 

To Wrap…

In the wide ecosystem of JavaScript, developers often face situations where they need to set a pause timer or delay a specified code before execution. Unfortunately, unlike other programming languages, JavaScript doesn’t have its built-in sleep () for delaying code execution and hence JavaScript sleep requires a different approach. Developers perform several methods and techniques to run the sleep () in JavaScript, from setTimeout () to Async/Await. These functions offer a useful method for delays in JavaScript instead of using third-party libraries and frameworks. Whether you are a beginner or a professional developer, learning these tactics will surely enhance your skills in JavaScript and make you a pro. Moreover, hire JavaScript developers for the professional execution of code with accurate delays and desired results.

ABOUT THE WRITER
Harshita Johari

Content Writer

Harshita is a proficient writer specializing in the IT industry. She can simplify complex topics in software development and digital marketing for diverse audiences. Her exceptional writing, editing and proofreading abilities ensure high quality content across blogs, web pages, and technical guides, enhancing communication, marketing and user engagement.