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.
Before proceeding with the techniques of using sleep in JavaScript, it is crucial to understand the role of delay in the execution:
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:
The most common application is to add a wait before running some code. This can be applied to:
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.
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.
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.
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 |
This common approach defines a function directly within the setTimeout call.
setTimeout(function() { console.log(“This message appears after 2 seconds.“); }, 2000); |
Highlight: setTimeout is not a core feature of JavaScript or ECMAScript. It exists in the window object of a browser environment.
Since there is no built-in sleep() function, there are several other ways to execute the same, starting with Async/Await.
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)); } |
async function delayedGreeting() { console.log(‘Welcome‘); await sleep(2000); // Pauses for 2 seconds console.log(‘World!‘); } delayedGreeting(); |
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.
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 demonstrateSleep(); |
Explanation:
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));:
await sleep(2000);:
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.
Promises in JavaScript introduce a delay in JavaScript with clear code and comprehensibility. It is used for complicated workflows and testing.
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); }); |
Promises are consumed using the .then(), .catch(), and .finally() methods.
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).“); }); |
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); }); |
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.
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.