How to create a Sleep function in React.js

avatar

Borislav Hadzhiev

Mon May 02 20222 min read

Create a Sleep function in React.js #

To create a sleep function in React:

  1. Define a function that takes the number of milliseconds as parameter.
  2. The function should return a Promise that gets resolved after the provided number of milliseconds.
App.js
import {useEffect} from 'react'; const sleep = ms => new Promise( resolve => setTimeout(resolve, ms) ); const App = () => { const handleClick = async event => { console.log('start'); await sleep(1000); console.log('end'); }; useEffect(() => { async function fetchData() { console.log('start'); await sleep(1000); console.log('end'); } fetchData(); }); return ( <div> <button onClick={handleClick}>Click</button> </div> ); }; export default App;

react sleep function

We created a sleep function that waits for N milliseconds before returning.

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

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 prefix it with the await keyword 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('start'); await sleep(1000); console.log('end'); };

The function logs start to the console, then sleeps for 1 seconds and logs end.

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

App.js
useEffect(() => { async function fetchData() { console.log('start'); await sleep(1000); console.log('end'); } fetchData(); });

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.