{"id":13446987,"url":"https://github.com/vitalets/await-timeout","last_synced_at":"2025-05-16T12:10:59.660Z","repository":{"id":60774990,"uuid":"109007292","full_name":"vitalets/await-timeout","owner":"vitalets","description":"A Promise-based API for setTimeout / clearTimeout","archived":false,"fork":false,"pushed_at":"2021-01-26T10:54:16.000Z","size":294,"stargazers_count":429,"open_issues_count":1,"forks_count":11,"subscribers_count":5,"default_branch":"master","last_synced_at":"2025-04-02T08:06:08.488Z","etag":null,"topics":["javascript","nodejs","promise","promisify","settimeout","timeout"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/vitalets.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-10-31T14:27:18.000Z","updated_at":"2024-12-30T18:46:50.000Z","dependencies_parsed_at":"2022-10-04T16:33:04.059Z","dependency_job_id":null,"html_url":"https://github.com/vitalets/await-timeout","commit_stats":null,"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vitalets%2Fawait-timeout","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vitalets%2Fawait-timeout/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vitalets%2Fawait-timeout/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/vitalets%2Fawait-timeout/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/vitalets","download_url":"https://codeload.github.com/vitalets/await-timeout/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248018050,"owners_count":21034047,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","nodejs","promise","promisify","settimeout","timeout"],"created_at":"2024-07-31T05:01:05.003Z","updated_at":"2025-04-09T10:03:26.123Z","avatar_url":"https://github.com/vitalets.png","language":"JavaScript","readme":"\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://user-images.githubusercontent.com/1473072/32229482-f90f07d2-be61-11e7-86f1-f9f555182292.png\"\u003e\n\u003c/div\u003e\n\u003ch1 align=\"center\"\u003eawait-timeout\u003c/h1\u003e\n\u003ch5 align=\"center\"\u003eA \u003ca href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise\"\u003ePromise\u003c/a\u003e-based API for setTimeout / clearTimeout\u003c/h5\u003e\n\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"https://github.com/vitalets/await-timeout/actions\"\u003e\u003cimg src=\"https://github.com/vitalets/await-timeout/workflows/autotests/badge.svg\" alt=\"Build Status\" /\u003e\u003c/a\u003e\n  \u003ca href=\"https://www.npmjs.com/package/await-timeout\"\u003e\u003cimg src=\"https://img.shields.io/npm/v/await-timeout.svg\" alt=\"Npm version\" /\u003e\u003c/a\u003e\n  \u003ca href=\"https://www.npmjs.com/package/await-timeout\"\u003e\u003cimg src=\"https://img.shields.io/npm/l/await-timeout.svg\" alt=\"License\" /\u003e\u003c/a\u003e\n\u003c/div\u003e\n\n## Contents\n* [Installation](#installation)\n* [Usage](#usage)\n* [API](#api)\n  * [new Timeout()](#new-timeout)\n  * [.set()](#setms-message--promise)\n  * [.wrap()](#wrappromise-ms-message--promise)\n  * [.clear()](#clear)\n  * [.id](#id--numbertimeout)\n  * [.delay](#delay--number)\n* [Motivation](#motivation)\n* [Related resources](#related-resources)\n* [License](#license)\n\n## Installation\n```bash\nnpm install await-timeout --save\n```\n\n## Usage\n1. Just wait some time:\n    ```js\n    import Timeout from 'await-timeout';\n\n    // wait 1000 ms and resolve\n    await Timeout.set(1000);\n    \n    // wait 1000 ms and reject with 'Timeout!'\n    await Timeout.set(1000, 'Timeout!');\n    ```\n\n2. Use `Timeout` instance inside `try...finally` block to make proper cleanup:\n    ```js\n    import Timeout from 'await-timeout';\n\n    const timer = new Timeout();\n    try {\n      await Promise.race([\n        fetch('https://example.com'),\n        timer.set(1000, 'Timeout!')\n      ]);\n    } finally {\n      timer.clear();\n    }\n    ```\n   \u003e Without a timer cleanup you may get unexpected effects in you code - as all promises in `Promise.race` \n   \u003e are get fulfilled.\n\n## API\n### new Timeout()\nConstructs new timeout instance. It does not start timer but creates variable for timer manipulation.\n```js\nconst timer = new Timeout();\n```\n\u003e Note: having separate `timer` variable is useful for clearing timeout in `finally` block \n\n### .set(delay, [rejectReason]) ⇒ `Promise`\nStarts new timer like `setTimeout()` and returns promise. The promise will be resolved after `delay` milliseconds:\n```js\nconst timer = new Timeout();\ntimer.set(1000)\n  .then(() =\u003e console.log('1000 ms passed.'));\n```\n\nIf you provide `rejectReason` - a timer promise will be rejected with specified reason:\n```js\n// rejects with Error: Timeout after 1000 ms:\ntimer.set(1000, 'Timeout after 1000 ms');\n  \n// above is actually shortcut for:\ntimer.set(1000).then(() =\u003e Promise.reject(new Error('Timeout after 1000 ms')));  \n```\n\nIf you need to just wait some time - use static version of `.set()`:\n```js\nawait Timeout.set(1000);\n```\n\n### .wrap(promise, delay, [rejectReason]) ⇒ `Promise`\nWraps existing promise with timeout:\n * returned promise automatically rejected after timeout \n * timeout automatically cleared if main promise resolves first\n```js\nasync function fetchWithTimeout() {\n  const promise = fetch('https://example.com');\n  return Timeout.wrap(promise, 1000, 'Timeout');\n}\n```\nActually it is a shortcut for:\n```js\nasync function fetchWithTimeout() {\n    const timer = new Timeout();\n    try {\n      const promise = fetch('https://example.com');\n      return await Promise.race([\n        promise,\n        timer.set(1000, 'Timeout')\n      ]);\n    } finally {\n      timer.clear();\n    }\n}\n```\n\n### .clear()\nClears existing timeout like `clearTimeout()`.\n```js\nconst timer = new Timeout();\ntimer.set(1000)\n  .then(() =\u003e console.log('This will never be called, because timeout is cleared on the next line'));\ntimer.clear();\n```\n\nWith [ES7 async / await] `.clear()` can be used in `finally` block:\n```js\nasync function foo() {\n  const timer = new Timeout();\n  try {\n    // some async stuff\n  } finally {\n    timer.clear();\n  }\n}\n```\n\n### .id ⇒ `?Number|?Timeout`\nReturns result of `setTimeout` call. That is `Number` timeout id in browser \nand [Timeout](https://nodejs.org/api/timers.html#timers_class_timeout) instance in Node.js.\n\n### .delay ⇒ `?Number`\nReturns last delay value used. Delay is useful for generating reject reason:\n```js\nconst timer = new Timeout();\ntimer.set(1000, () =\u003e new Error(`Timeout: ${timer.delay}`));\n```\n\n## Motivation\nBefore making this library I've researched [several similar packages on Npm](https://www.npmjs.com/search?q=promise%20timeout).\nBut no one satisfied all my needs together:\n\n1. Convenient way to cancel timeout. I typically use it with [Promise.race()] and don't want timer to trigger\n   if main promise is resolved first.\n2. API similar to `setTimeout` / `clearTimeout`. I get used to these functions and would like to have mirror syntax.\n3. Easy rejection of timeout promise. Passing error message should be enough.\n4. No monkey-patching of Promise object.\n5. Zero dependencies.\n\n## Related resources\n* [The right way to clear timeout in Promise.race()](https://jslive.com/p/3x2x9h-the-right-way-to-clear-timeout-in-promiserace)\n* [Applying a timeout to your promises](https://italonascimento.github.io/applying-a-timeout-to-your-promises/)\n* [How to make a promise from setTimeout](https://stackoverflow.com/questions/22707475/how-to-make-a-promise-from-settimeout)\n* [Is there a version of setTimeout that returns an ES6 promise?](https://stackoverflow.com/questions/34255351/is-there-a-version-of-settimeout-that-returns-an-es6-promise)\n\n## License\nMIT @ [Vitaliy Potapov](https://github.com/vitalets)\n\n[Promise]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise\n[Promise.race()]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/race\n[ES7 async / await]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function\n","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvitalets%2Fawait-timeout","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fvitalets%2Fawait-timeout","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fvitalets%2Fawait-timeout/lists"}