Pause an Async Function for 3 Seconds in Node.js
How can you pause an async function for 3 seconds in Node.js?
Add this line of code in your function wherever you want the pause to occur:
await new Promise(r => setTimeout(r, 3000));
This code creates a Promise and resolves it after 3000
milliseconds (or 3
seconds) using a setTimeout()
function.
You could use it in your function like this:
const uploadImage = async function() {
// do some stuff
await new Promise(r => setTimeout(r, 3000));
// do some more stuff
};
Also, here's an implementation of a sleep()
function using this method:
const sleep = function(seconds) {
// convert seconds to milliseconds for the setTimeout() function
const milliseconds = seconds * 1000;
return new Promise(r => setTimeout(r, milliseconds));
};
This function takes a seconds
parameter and resolves/returns a promise after that amount of time has elapsed. When called, it will pause only the current async function it's inside of.
Here's how you'd use it:
const uploadImage = async function() {
// do some stuff
await sleep(3);
// do some more stuff
};
Thanks for reading and happy coding!