How To Turn SetTimeout and SetInterval Into Promises

Learn how to promisify JavaScript timers

Mike Cronin
Level Up Coding
Published in
3 min readJul 27, 2020

--

If you’ve ever wanted to then or await JavaScript’s setTimeout or setInterval, functions, you’re not alone. I’ve had to use these methods a lot at work to deal with some…interesting…third party behavior, so I’ve finally become familiar with promisifying functions. setTimeout may be simple, and setInterval is a tad trickier, so make sure you understand promises.

TL:DR; the code

const sleep = async (ms) => {
return new Promise(resolve => setTimeout(resolve, ms));
}
const asyncInterval = async (callback, ms, triesLeft = 5) => {
return new Promise((resolve, reject) => {
const interval = setInterval(async () => {
if (await callback()) {
resolve();
clearInterval(interval);
} else if (triesLeft <= 1) {
reject();
clearInterval(interval);
}
triesLeft--;
}, ms);
});
}

There it is, if you want to see why, check below! But if that’s all you need, glad I could help!

How to promisify setTimeout

Take this code:

const foo = () => {
setTimeout(() => {
console.log('Callback based stuff');
console.log('yet

--

--

I’m Mostly Focused on JS and web development, but anything coding related is fair game