#Promises#Async

Time Out an Async Function

Wrap an async function so it gives up after a deadline — the building block behind every request timeout.

By Pratik RaiMedium

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

Input:

JSfile.javascript
1const lookup = timeLimit(async (word, ms) => { 2 await new Promise((r) => setTimeout(r, ms)); 3 return word.toUpperCase(); 4}, 200); 5 6lookup('fast', 80).then(console.log); 7lookup('slow', 350).catch(console.log);

Output:

FAST
Timed out

Both calls get the same 200ms budget. The first finishes at 80ms and its value passes straight through; the second would need 350ms, so it is rejected when the budget runs out at 200ms.

Constraints

  • 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.

How to solve it

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

JSfile.javascript
1function timeLimit(fn, t) { 2 return function (...args) { 3 return new Promise((resolve, reject) => { 4 const timer = setTimeout(() => reject('Timed out'), t); 5 fn.apply(this, args).then(resolve, reject).finally(() => clearTimeout(timer)); 6 }); 7 }; 8}

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.

Goal: Reject with "Timed out" past the deadline, and pass everything else through untouched.

Frequently asked questions

How do you add a timeout to a promise?
Race the promise against a timer that rejects. Promise.race settles with whichever finishes first, and because a promise settles only once the loser is ignored automatically.
Does a timeout cancel the underlying work?
No. The original promise carries on and its result is discarded — the timeout only stops you waiting. Cancelling a real request needs AbortController passed to fetch.
Why clear the timer after the race settles?
A pending timer keeps the event loop alive, which delays process exit in Node and leaks a callback in a long-lived page. Clearing it in finally covers both the success and failure paths.
Should a timeout replace the original error?
No. If the wrapped function rejects on its own, that rejection should pass through unchanged. Replacing it with a generic timeout hides the real cause and makes the failure much harder to debug.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Promise Pool With a Concurrency Limit

Run a list of async tasks with a hard limit on how many are in flight at once — the concurrency control Promise.all does not give you.

JavaScript · ES6 — Pratik Rai ·

JavaScript

Promisify a Callback Function

Convert a Node-style (error, value) callback API into one that returns a promise.

JavaScript · ES6 — Pratik Rai ·

JavaScript

Resolve Promises Sequentially

Run promises one after another and collect the results in order — built with .then chaining, no async/await.

JavaScript · ES6 — Pratik Rai ·