Synchronous delay
// syncWait.js
export default function syncWait(ms = 1000) {
const end = Date.now() + ms
while (Date.now() < end) continue
}
import syncWait from '/functions/syncWait'
function SynchDelay() {
const sayHiWithDelay = () => {
syncWait(2000)
alert('hi')
}
return <>
<button onClick={sayHiWithDelay}>Say 'hi' with delay</button>
</>
}
Promise with delay
// sleeper.js
function sleeper(ms = 1000) {
return new Promise(resolve => setTimeout(() => resolve('done'), ms))
}
// the usage
axios('https://jsonplaceholder.typicode.com/posts/1')
.then(() => sleeper(3000))
.then(res => alert('Title: ' + res.data.title))
Full code
import axios from 'axios'
import sleeper from '../../../../helpers/functions/sleeper'
function Component() {
return (
<>
<button
onClick={() => {
alert('start request')
axios('https://jsonplaceholder.typicode.com/posts/1')
.then(res => alert(`Title: ${res.data.title}`))
.catch(err => alert(JSON.stringify(err)))
}}
>
Get respond from server
</button>
<br/>
<button
onClick={() => {
alert('start request with 3s delay')
axios('https://jsonplaceholder.typicode.com/posts/1')
.then(sleeper(3000))
.then(res => alert(`Title: ${res.data.title}`))
.catch(err => alert(JSON.stringify(err)))
}}
>
Get respond from server with delay
</button>
</>
)
}
Delay an api response by 5 sec
app.get('/api', async (_req: Req, res: Res) => {
await new Promise(resolve => {
setTimeout(() => resolve('done'), 5000)
})
return res.json({ url: '/api', data: 'some data' })
})