Skip to content

withTimeout

withTimeout<T>(task, ms): Promise<T>

Races a promise (or promise-returning function) against a manual timeout. The timer is cleared as soon as the task settles.

T

Return type

The work to perform: either a Promise or a function that returns a Promise.

Promise<T> | () => Promise<T>

number

Timeout in milliseconds after which the returned promise rejects.

Promise<T>

A promise that resolves with the task’s result, or rejects with an Error(Timeout after ${ms}ms) if the timer elapses first.

// Race a fetch against a 2-second timeout
withTimeout(fetch('/api/data'), 2000)
.then(res => res.json())
.then(data => console.log('Received:', data))
.catch(err => {
if (err.message.startsWith('Timeout')) {
console.error('Request timed out');
} else {
console.error('Fetch error:', err);
}
});
// Use a function that returns a Promise
withTimeout(() => performLongComputation(), 5000)
.then(result => console.log('Result:', result))
.catch(err => console.error(err));