Javascript setTimeout with async callback
Published on: 6th Sep 2022
Updated on: 4th Aug 2025
Overview
When async version is added to some built-in functions, it can be very confusing whether the function supports an async callback or not.
For example, Array.forEach()
does not support async callback while other functions might be supported async callback.
Let test out setTimeout()
with async callback and see if it works.
Experiment setTimeout() with an async callback
Let says we have a function that returns a Promise
object which looks like this:
function test1(){
return new Promise(function(resolve, reject) {
resolve('helo work');
});
}
And we are going to execute the above function within setTimeout()
. Do you think it work?
setTimeout(async () => {
console.log('timeout..running');
console.log(await test1());
}, 100);
The result is - yes, it works perfectly.
Side track
04.Aug.2025: to make your async program to sleep for a while, this can be done easily. You need a function that returns a Promise
object and using setTimeout
to call resolve
which looks like below:
function sleep(sleep_ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, sleep_ms);
});
}
To make the async program to sleep for 500ms, do this:
await sleep(500);
Since this is an async function, the calls to sleep()
will not block the event loop. In fact, the sleep()
function will schedule the current process to continue after 500ms. This sleep()
function is very useful.
We mainly use this sleep()
to wait for another process to complete writing to a file and close it. For example, we are waiting for a PDF file generation process to be completed. So, we make our program to check if we can lock the PDF file exclusively in every 200ms and once we gain the lock, the next process will be started.
Conclusion
The ongoing upgrade to the built-in functions make it difficult for the programmer to catch up. But, it is still fun to write program using JavaScript because you learn new stuffs everyday and you will find new way on using async function.
Back to #JAVASCRIPT blog
Back to #blog listing
Author
Lau Hon Wan, software developer.