docs/reference/promise/timeout.md
Returns a Promise that throws a TimeoutError after the specified time.
await timeout(ms);
timeout(ms)Use timeout when you want to throw a timeout error after a specific time has passed. It's useful when used together with Promise.race() to set time limits on tasks.
import { timeout } from 'es-toolkit/promise';
// Basic usage - throws TimeoutError after 1 second
try {
await timeout(1000);
console.log('This code will not execute');
} catch (error) {
console.log('Timeout error occurred:', error.message); // 'The operation was timed out'
}
You can use it with Promise.race() to set time limits on tasks:
async function fetchWithTimeout(url: string) {
try {
const result = await Promise.race([
fetch(url),
timeout(5000), // 5 second limit
]);
return result;
} catch (error) {
if (error.name === 'TimeoutError') {
console.log('Request is taking too long');
}
throw error;
}
}
You can also use it when you want to fail the entire operation if any of multiple asynchronous tasks don't complete within the specified time.
async function multipleOperationsWithTimeout() {
try {
await Promise.race([
Promise.all([fetch('/api/data1'), fetch('/api/data2'), fetch('/api/data3')]),
timeout(3000), // 3 second limit for all tasks
]);
console.log('All tasks completed on time');
} catch (error) {
console.log('Tasks did not complete on time');
}
}
ms (number): The amount of time in milliseconds until the TimeoutError is thrown.(Promise<never>): Returns a Promise that rejects with a TimeoutError after the specified time.
Throws TimeoutError after the specified time has passed.