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.
Type Parameters
Section titled “Type Parameters”T
Return type
Parameters
Section titled “Parameters”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.
Returns
Section titled “Returns”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.
Examples
Section titled “Examples”// Race a fetch against a 2-second timeoutwithTimeout(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 PromisewithTimeout(() => performLongComputation(), 5000) .then(result => console.log('Result:', result)) .catch(err => console.error(err));