Last updated: Apr 7, 2024
Reading time·2 min
To create a delay function in React:
setTimeout
method to resolve a Promise after the provided number of
milliseconds.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;
We created a delay
function that waits for N milliseconds before resolving a
Promise.
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
.
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.
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.
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.
useEffect
The same approach can be used in the
useEffect hook but we can't mark
the function we pass to useEffect
as async
.
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
.
If you need to wait for the state to update, click on the link and follow the instructions.
You can also use the Promise.then()
syntax instead of async/await
when using
your sleep
function.
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;
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.