Design Converter
Education
Last updated on Mar 4, 2025
•5 mins read
Last updated on Mar 4, 2025
•5 mins read
Want to pause execution in a React app for a few seconds?
JavaScript doesn’t have a built-in sleep function, but you can still introduce delays using promises or setTimeout.
Handling delays helps control asynchronous tasks, preventing issues like race conditions or unnecessary re-renders. This blog explains how to create a reusable React sleep function with simple code examples and clear explanations.
Let’s break it down step by step!
When working with async functions, there are cases where delaying execution becomes necessary. Some common scenarios include:
• Waiting for an API response before updating the UI.
• Delaying state changes in a React component.
• Introducing a delay between retries for failed requests.
• Simulating network latency for testing purposes.
Since JavaScript does not have a built-in sleep function, developers must create one using promise-based techniques.
A JavaScript sleep function can be built using new Promise and the setTimeout function. The promise resolve technique helps to pause execution by returning a Promise object that resolves after a specified amount of time.
1function sleep(milliseconds) { 2 return new Promise(resolve => setTimeout(resolve, milliseconds)); 3}
• The function creates a new Promise.
• The first argument of setTimeout is a callback function that calls resolve.
• The setTimeout resolve happens after the given milliseconds.
This allows the function to be used inside async functions using await.
Since JavaScript executes code asynchronously, the await sleep() method helps introduce delays inside async functions without blocking the execution of other tasks.
1async function fetchData() { 2 console.log("Fetching data..."); 3 await sleep(2000); 4 console.log("Data fetched after delay."); 5} 6 7fetchData();
1Fetching data... 2(wait for 2 seconds) 3Data fetched after delay.
This example demonstrates how the await sleep method helps in delaying an execution inside an async function.
In a React application, introducing a delay function can improve user experience. The following example demonstrates how to use the sleep function inside a React component.
1import React, { useState } from "react"; 2 3function SleepComponent() { 4 const [message, setMessage] = useState("Click the button to start delay"); 5 6 async function handleClick() { 7 setMessage("Waiting..."); 8 await sleep(3000); 9 setMessage("Wait over!"); 10 } 11 12 function sleep(milliseconds) { 13 return new Promise(resolve => setTimeout(resolve, milliseconds)); 14 } 15 16 return ( 17 <div> 18 <p>{message}</p> 19 <button onClick={handleClick}>Start Delay</button> 20 </div> 21 ); 22} 23 24export default SleepComponent;
• The React component uses useState to manage the message.
• The handleClick function executes when the button is clicked, triggering a delay function.
• The sleep function introduces a pause execution before updating the value of message.
Another practical use of a delay function is introducing delays between API requests to avoid excessive server load.
1async function fetchWithDelay(url) { 2 console.log("Requesting data..."); 3 const response = await fetch(url); 4 const data = await response.json(); 5 6 console.log("Data received:", data); 7 console.log("Pausing before next request..."); 8 9 await sleep(5000); 10 11 return data; 12}
This approach ensures a pause execution between API requests, preventing excessive network traffic.
The diagram shows how the JavaScript sleep function delays execution using new Promise and setTimeout resolve.
In a React component, the useEffect hook can be combined with a delay function to introduce controlled delays.
1import React, { useState, useEffect } from "react"; 2 3function DelayedMessage() { 4 const [message, setMessage] = useState("Loading..."); 5 6 useEffect(() => { 7 async function updateMessage() { 8 await sleep(3000); 9 setMessage("Data Loaded"); 10 } 11 updateMessage(); 12 }, []); 13 14 function sleep(milliseconds) { 15 return new Promise(resolve => setTimeout(resolve, milliseconds)); 16 } 17 18 return <p>{message}</p>; 19} 20 21export default DelayedMessage;
• The useEffect hook triggers when the React component mounts.
• The updateMessage async function introduces a pause execution before updating the UI.
Avoid using a while loop to introduce delays, as it blocks the JavaScript event loop.
1// Bad practice: Blocks execution 2function sleep(milliseconds) { 3 const start = Date.now(); 4 while (Date.now() - start < milliseconds); 5}
Instead, always use a Promise-based approach.
If await is omitted, the execution will not wait for the promise resolve.
1async function incorrectSleepUsage() { 2 console.log("Before sleep"); 3 sleep(2000); // Incorrect usage 4 console.log("After sleep"); // Executes immediately 5}
To fix this, always use await sleep(time).
Mastering React Sleep techniques enables developers to create seamless asynchronous operations within their applications. Using a JavaScript sleep function, combined with async functions and promise resolve, ensures controlled execution of tasks. Whether managing API calls, handling UI updates, or controlling event delays, a well-implemented sleep function improves efficiency in a React application.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.