es-toolkit/docs/reference/promise/withTimeout.md
Seung Ju b31b3a6964
feat(withTimeout): add withTimeout function (#210)
* feat(timeout): add timeout function

* feat(timeout): timeout to withTimeout

* Update docs/ko/reference/promise/withTimeout.md

* Update docs/ko/reference/promise/withTimeout.md

* feat(timeout): timeout, withTimeout

* Update docs/ko/reference/promise/timeout.md

* Update docs/ko/reference/promise/timeout.md

* Update withTimeout.ts

* Update timeout.ts

* Apply suggestions from code review

* Update withTimeout.md

* Update withTimeout.spec.ts

* Update src/promise/withTimeout.spec.ts

---------

Co-authored-by: Sojin Park <raon0211@gmail.com>
Co-authored-by: Sojin Park <raon0211@toss.im>
2024-07-18 21:37:33 +09:00

817 B

withTimeout

Executes an async function and enforces a timeout.

If the promise does not resolve within the specified time, the timeout will trigger and the returned promise will be rejected.

Signature

function withTimeout<T>(run: () => Promise<T>, ms: number): Promise<T>;

Parameters

  • run (() => Promise<T>): A function that returns a promise to be executed.
  • ms (number): The timeout duration in milliseconds.

Returns

(Promise<T>): A promise that resolves with the result of the run function or rejects if the timeout is reached.

Examples

Basic Usage

try {
  await withTimeout(() => new Promise(() => {}), 1000); // Timeout exception after 1 second
} catch (error) {
  console.error(error); // Will log 'The operation was timed out'
}