How to create a Delay function in React

avatar

Borislav Hadzhiev

Mon May 02 20222 min read

banner

Photo by Kinder Land

Create a Delay function in React #

To create a delay function in React:

  1. Define a function that takes the number of milliseconds as 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

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 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.

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('before'); await delay(1000); console.log('after'); } 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.