I want to implement a sleep function that functions like the following like this:
console.log(123)
slepp(2000)
console.log(456)
run it:
123
waiting two seconds...
456
I want to get a solution about sleep function implements
I want to implement a sleep function that functions like the following like this:
console.log(123)
slepp(2000)
console.log(456)
run it:
123
waiting two seconds...
456
I want to get a solution about sleep function implements
Did this myself just the other day on a project.
function sleep(delay) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, delay);
});
}
You can use by: await sleep(2000)
for a 2 second delay.
Here's the function that I add to almost every project I have:
/**
* Async function to sleep for `ms` amound of milliseconds.
* @param ms - time to sleep in milliseconds
* @returns `Promise<void>` after the sleep time has passed.
*/
export async function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, ms);
});
}
Edit: Looks like @John Detlefs beat me to it by 2 minutes, didn't notice it while the question was already open :)