Time Out an Async Function
Write timeLimit(fn, t). It returns a wrapper that takes the same arguments as fn and settles the same way fn does — unless fn is still running after t milliseconds. In that case the wrapper gives up and rejects with "Timed out", a plain string rather than an Error.
Examples
const lookup = timeLimit(async (word, ms) => {
await new Promise((r) => setTimeout(r, ms));
return word.toUpperCase();
}, 200);
lookup('fast', 80).then(console.log);
lookup('slow', 350).catch(console.log);FAST
Timed outConstraints
- fn is an async function, so calling it always gives back a promise
- t is a positive number of milliseconds
Notes
- A rejection from fn itself must pass through unchanged rather than becoming a timeout.
- Clear the timer once the race settles, either way.
Hints
Editorial: Time Out an Async Function
Racing a timer
Every network call needs a deadline. Without one a hung request leaves a spinner on screen forever, because a promise that never settles never rejects either.
Approach
Two things are racing: the real call, and a timer that rejects. Promise.race says exactly that — whichever settles first wins, and the loser is ignored because a promise settles only once.
Implementation
function timeLimit(fn, t) { return function (...args) { return new Promise((resolve, reject) => { const timer = setTimeout(() => reject('Timed out'), t); fn.apply(this, args).then(resolve, reject).finally(() => clearTimeout(timer)); }); }; }
Worth knowing
timeLimit returns a function, not a promise. Nothing starts until that function is called, which is what lets you wrap once and reuse.
Clearing the timer in finally matters more than it looks: a pending timer keeps the event loop alive and, in Node, delays process exit. It also means a rejection from fn itself passes straight through rather than being replaced by a timeout.