{"id":15970,"library":"await-timeout","title":"await-timeout","description":"await-timeout, currently at version 1.1.1, offers a Promise-based API for handling `setTimeout` and `clearTimeout` in JavaScript, making it particularly useful within `async/await` constructs. It simplifies common asynchronous patterns such as adding timeouts to network requests or other long-running operations. The library provides both static methods like `Timeout.set(ms)` for simple delays and instance methods (`new Timeout().set(ms)`) for more controlled scenarios, including wrapping existing promises with timeouts using `Timeout.wrap(promise, ms, rejectReason)`. A key differentiator is its emphasis on proper resource management, advising the use of `.clear()` within `finally` blocks to prevent unhandled promise rejections or 'unexpected effects' when dealing with `Promise.race`. While a specific release cadence isn't detailed, its stable 1.x version implies a mature and focused utility for precise timeout management in asynchronous codebases.","status":"active","version":"1.1.1","language":"javascript","source_language":"en","source_url":"git://github.com/vitalets/await-timeout","tags":["javascript","timeout","promise","promise-api","promises","settimeout","cleartimeout"],"install":[{"cmd":"npm install await-timeout","lang":"bash","label":"npm"},{"cmd":"yarn add await-timeout","lang":"bash","label":"yarn"},{"cmd":"pnpm add await-timeout","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"While CommonJS `require` works, ESM `import` is the idiomatic way for modern Node.js and bundlers.","wrong":"const Timeout = require('await-timeout');","symbol":"Timeout","correct":"import Timeout from 'await-timeout';"},{"note":"For simple delays without the need for manual clearing, the static `set` method is more concise. Using an instance is only necessary if you intend to manually clear the timer.","wrong":"await new Timeout().set(1000);","symbol":"Timeout.set (static)","correct":"await Timeout.set(1000);"},{"note":"The `Timeout` class must be instantiated with `new` to create a new timer object for instance methods like `.set()` and `.clear()`.","wrong":"const timer = Timeout();","symbol":"Timeout (instance)","correct":"const timer = new Timeout();"}],"quickstart":{"code":"import Timeout from 'await-timeout';\n\nasync function fetchWithTimeoutExample() {\n  const timer = new Timeout();\n  try {\n    console.log('Attempting to fetch data with a 1-second timeout...');\n    const dataPromise = fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json());\n    const result = await Promise.race([\n      dataPromise,\n      timer.set(1000, new Error('Fetch operation timed out!')) // Rejects after 1 second\n    ]);\n\n    if (result instanceof Error) {\n      throw result; // Propagate the timeout error\n    }\n    console.log('Data fetched successfully:', result.title);\n  } catch (error) {\n    console.error('Operation failed:', error.message);\n  } finally {\n    timer.clear(); // Essential cleanup to prevent resource leaks and 'unexpected effects'\n    console.log('Timeout timer cleared.');\n  }\n}\n\nasync function simpleDelayExample() {\n  console.log('\\nStarting a 500ms delay...');\n  await Timeout.set(500); // Static method for a simple awaitable delay\n  console.log('Delay finished after 500ms.');\n}\n\nfetchWithTimeoutExample();\nsimpleDelayExample();","lang":"javascript","description":"Demonstrates using `await-timeout` to add a timeout to a fetch request with `Promise.race` and proper cleanup, alongside a simple static delay."},"warnings":[{"fix":"Ensure `timer.clear()` is called within a `try...finally` block after `Promise.race` or any operation involving an instance-based timer.","message":"When using `Timeout` instances, especially with `Promise.race`, it is crucial to always call `.clear()` in a `finally` block. Failing to do so can lead to 'unexpected effects' or unhandled promise rejections, as the internal `setTimeout` might still fire even if the race condition is met by another promise.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always chain a `.catch()` to the promise returned by `timer.set(delay, rejectReason)` or wrap the `await` call in a `try...catch` block if the promise is configured to reject.","message":"If `Timeout.set(delay, rejectReason)` is used to create a rejecting promise and that promise is not caught or handled, it will result in an 'Unhandled Promise Rejection' error in Node.js or the browser console.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Familiarize yourself with the internal implementation of `wrap` (as shown in the README) to understand how it uses `Promise.race` and `timer.clear()` to ensure proper behavior.","message":"The `Timeout.wrap(promise, delay, rejectReason)` static method is a convenient shortcut, but it internally creates and manages a `Timeout` instance. While it handles clearing the timer automatically, developers should understand its behavior to avoid misuse or misinterpreting its interactions in complex promise chains.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-21T00:00:00.000Z","next_check":"2026-07-20T00:00:00.000Z","problems":[{"fix":"Add a `.catch()` block to the promise returned by `Timeout.set()` or wrap the `await Timeout.set()` call in a `try...catch` statement to handle the rejection.","cause":"A `Timeout.set(ms, 'Timeout!')` promise was rejected, but there was no `.catch()` handler or surrounding `try...catch` block to manage it.","error":"UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: X): Error: Timeout!"},{"fix":"Use `const timer = new Timeout();` to create an instance, ensuring `Timeout` is correctly imported as a class: `import Timeout from 'await-timeout';`.","cause":"Attempting to call `Timeout()` directly without the `new` keyword, or incorrect import of the default export.","error":"TypeError: Timeout is not a constructor"}],"ecosystem":"npm"}