How to create a Delay (Sleep) function in React

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Create a Delay (Sleep) function in React

To create a delay function in React:

  1. Define a function that takes the number of milliseconds as a parameter.
  2. Use the setTimeout method to resolve a Promise after the provided number of milliseconds.
App.js
import {useEffect} from 'react'; const delay = ms => new Promise( resolve => setTimeout(resolve, ms) ); const App = () => { const handleClick = async event => { console.log('before'); await delay(1000); console.log('after'); }; useEffect(() => { async function makeRequest() { console.log('before'); await delay(1000); console.log('after'); } makeRequest(); }); return ( <div> <button onClick={handleClick}>Click</button> </div> ); }; export default App;

react delay function

The code for this article is available on GitHub

We created a delay function that waits for N milliseconds before resolving a Promise.

App.js
const delay = ms => new Promise( resolve => setTimeout(resolve, ms) );

The concept of a delay function is also commonly known as a sleep function.

If you find the naming more intuitive, rename your function to sleep.

App.js
const sleep = ms => new Promise( resolve => setTimeout(resolve, ms) );

A sleep or delay function is used to wait for N milliseconds before performing an action.

The function takes the number of milliseconds as a parameter and uses the setTimeout method to wait for the specified number of milliseconds before resolving a Promise.

The function returns a Promise, so in order to use it we have to either await the result or use the .then() syntax.

We marked the handleClick function as async, so we are able to use the await keyword in it.

App.js
const handleClick = async event => { console.log('before'); await delay(1000); console.log('after'); };

The function logs before to the console, then waits for 1 seconds and logs after.

I've also written a detailed guide on how to clear a timeout or an interval in React.

# Using the sleep function inside of useEffect

The same approach can be used in the useEffect hook but we can't mark the function we pass to useEffect as async.

App.js
useEffect(() => { async function fetchData() { console.log('before'); await delay(1000); console.log('after'); } fetchData(); });
The code for this article is available on GitHub

Async functions return a Promise object but the useEffect hook can only return a cleanup function, so we have to define our async function inside useEffect.

If you need to wait for the state to update, click on the link and follow the instructions.

# Using the sleep function with promises in React

You can also use the Promise.then() syntax instead of async/await when using your sleep function.

App.js
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); const App = () => { const handleClick = async event => { console.log('before'); sleep(1000).then(() => { console.log('this ran after 1 second'); console.log('bobbyhadz.com'); }); }; return ( <div> <button onClick={handleClick}>Click</button> </div> ); }; export default App;

react delay function

The code for this article is available on GitHub

The sleep function returns a Promise, so we can directly call the then() method on the result.

The sleep function waits for 1 second in the example, so the .then() method gets invoked after 1 second.

The code in the callback function we passed to .then() is run after the promise in the sleep function has resolved.

I've also written a detailed article on how to fetch data on button click.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.