• Stars
    star
    428
  • Rank 101,481 (Top 2 %)
  • Language
    JavaScript
  • Created about 7 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Promise-based API for setTimeout / clearTimeout

await-timeout

A Promise-based API for setTimeout / clearTimeout
Build Status Npm version License

Contents

Installation

npm install await-timeout --save

Usage

  1. Just wait some time:

    import Timeout from 'await-timeout';
    
    // wait 1000 ms and resolve
    await Timeout.set(1000);
    
    // wait 1000 ms and reject with 'Timeout!'
    await Timeout.set(1000, 'Timeout!');
  2. Use Timeout instance inside try...finally block to make proper cleanup:

    import Timeout from 'await-timeout';
    
    const timer = new Timeout();
    try {
      await Promise.race([
        fetch('https://example.com'),
        timer.set(1000, 'Timeout!')
      ]);
    } finally {
      timer.clear();
    }

    Without a timer cleanup you may get unexpected effects in you code - as all promises in Promise.race are get fulfilled.

API

new Timeout()

Constructs new timeout instance. It does not start timer but creates variable for timer manipulation.

const timer = new Timeout();

Note: having separate timer variable is useful for clearing timeout in finally block

.set(delay, [rejectReason]) ⇒ Promise

Starts new timer like setTimeout() and returns promise. The promise will be resolved after delay milliseconds:

const timer = new Timeout();
timer.set(1000)
  .then(() => console.log('1000 ms passed.'));

If you provide rejectReason - a timer promise will be rejected with specified reason:

// rejects with Error: Timeout after 1000 ms:
timer.set(1000, 'Timeout after 1000 ms');
  
// above is actually shortcut for:
timer.set(1000).then(() => Promise.reject(new Error('Timeout after 1000 ms')));  

If you need to just wait some time - use static version of .set():

await Timeout.set(1000);

.wrap(promise, delay, [rejectReason]) ⇒ Promise

Wraps existing promise with timeout:

  • returned promise automatically rejected after timeout
  • timeout automatically cleared if main promise resolves first
async function fetchWithTimeout() {
  const promise = fetch('https://example.com');
  return Timeout.wrap(promise, 1000, 'Timeout');
}

Actually it is a shortcut for:

async function fetchWithTimeout() {
    const timer = new Timeout();
    try {
      const promise = fetch('https://example.com');
      return await Promise.race([
        promise,
        timer.set(1000, 'Timeout')
      ]);
    } finally {
      timer.clear();
    }
}

.clear()

Clears existing timeout like clearTimeout().

const timer = new Timeout();
timer.set(1000)
  .then(() => console.log('This will never be called, because timeout is cleared on the next line'));
timer.clear();

With ES7 async / await .clear() can be used in finally block:

async function foo() {
  const timer = new Timeout();
  try {
    // some async stuff
  } finally {
    timer.clear();
  }
}

.id ⇒ ?Number|?Timeout

Returns result of setTimeout call. That is Number timeout id in browser and Timeout instance in Node.js.

.delay ⇒ ?Number

Returns last delay value used. Delay is useful for generating reject reason:

const timer = new Timeout();
timer.set(1000, () => new Error(`Timeout: ${timer.delay}`));

Motivation

Before making this library I've researched several similar packages on Npm. But no one satisfied all my needs together:

  1. Convenient way to cancel timeout. I typically use it with Promise.race() and don't want timer to trigger if main promise is resolved first.
  2. API similar to setTimeout / clearTimeout. I get used to these functions and would like to have mirror syntax.
  3. Easy rejection of timeout promise. Passing error message should be enough.
  4. No monkey-patching of Promise object.
  5. Zero dependencies.

Related resources

License

MIT @ Vitaliy Potapov

More Repositories

1

x-editable

In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery
JavaScript
6,477
star
2

react-native-extended-stylesheet

Extended StyleSheets for React Native
JavaScript
2,926
star
3

github-trending-repos

Track GitHub trending repositories in your favorite programming language by native GitHub notifications!
HTML
2,678
star
4

angular-xeditable

Edit in place for AngularJS
HTML
1,913
star
5

awesome-smart-tv

⚡A curated list of awesome resources for building Smart TV apps
1,072
star
6

checklist-model

AngularJS directive for list of checkboxes
HTML
1,051
star
7

websocket-as-promised

A Promise-based API for WebSockets
JavaScript
595
star
8

bootstrap-editable

This plugin no longer supported! Please use x-editable instead!
JavaScript
558
star
9

playwright-bdd

BDD testing with Playwright runner
TypeScript
302
star
10

combodate

Dropdown date and time picker
JavaScript
208
star
11

autotester

Chrome extension that allows to develop and run automation tests right in browser
JavaScript
170
star
12

clockface

Clockface timepicker for Twitter Bootstrap
CSS
168
star
13

awesome-browser-extensions-and-apps

⚡A curated list of awesome resources for building browser extensions and apps
126
star
14

babel-plugin-runtyper

⚡️ Runtime type-checker for JavaScript
JavaScript
116
star
15

x-editable-yii

Yii extension for creating editable elements
JavaScript
112
star
16

docker-tizen-webos-sdk

Docker image with Samsung Tizen CLI and LG webOS CLI
Dockerfile
94
star
17

tinkoff-invest-api

Node.js SDK для работы с Tinkoff Invest API
HTML
44
star
18

bro-fs

Promise-based HTML5 Filesystem API similar to Node.js fs module
JavaScript
43
star
19

yii-bootstrap-editable

Yii extension for Bootstrap-editable plugin
JavaScript
31
star
20

alice-renderer

Node.js библиотека для формирования ответов в навыках Яндекс Алисы.
JavaScript
30
star
21

playwright-bdd-example

Example project that uses playwright-bdd to run BDD tests
TypeScript
30
star
22

playwright-magic-steps

Auto-transform JavaScript comments into Playwright steps
TypeScript
29
star
23

alice-workshop

Воркшоп по разработке навыка для Алисы на Node.js
JavaScript
28
star
24

js-testrunners-bench

JavaScript test-runners benchmark
JavaScript
27
star
25

groupgridview

Yii extension to group data in your grid
PHP
24
star
26

lazy-model

AngularJS directive that works like `ng-model` but accept changes only when form is submitted (otherwise changes are cancelled)
JavaScript
21
star
27

tinkoff-robot

Пример торгового робота для Tinkoff Invest API (Node.js)
TypeScript
21
star
28

chnl

JavaScript event channels compatible with Chrome extensions API
JavaScript
19
star
29

docker-stack-wait-deploy

A script waiting for docker stack deploy command to complete.
Shell
18
star
30

playwright-network-cache

Cache and mock network requests in Playwright
TypeScript
17
star
31

alice-tester

Библиотека для автоматического тестирования навыков Алисы на Node.js.
JavaScript
14
star
32

promise-controller

Advanced control of JavaScript promises
JavaScript
13
star
33

controlled-promise

Advanced control of JavaScript promises
JavaScript
13
star
34

mocha-es6-modules

Running Mocha tests in the browser with ES6 Modules support
JavaScript
12
star
35

yandex-cloud-deploy-fn

CLI для деплоя функций в Yandex Cloud на Node.js
TypeScript
11
star
36

tinkoff-local-broker

Локальный сервер для тестирования торговых роботов на Tinkoff Invest API
TypeScript
9
star
37

alice-cloud-proxy

Готовая облачная функция для развертывания своего прокси-навыка для Алисы
JavaScript
9
star
38

throw-utils

Helpers for error throwing
TypeScript
5
star
39

wait-for-cmd

A pure shell script waiting for provided command to exit with zero code
Shell
5
star
40

selgridview

Yii extension to keep selected rows in CGridView when sorting and pagination
JavaScript
5
star
41

alice-protocol

JSON схемы запросов и ответов в навыках Алисы
JavaScript
5
star
42

alice-skill-starter

Быстрый старт навыка для Алисы на Node.js
JavaScript
5
star
43

ydb-sdk-lite

Lightweight implementation of Yandex Database SDK for Node.js
JavaScript
4
star
44

flat-options

One-level options with default values and validation
JavaScript
4
star
45

yandex-cloud-fn

Хелперы для функций в Yandex Cloud (Node.js)
TypeScript
4
star
46

alice-testing-example

Пример функционального тестирования навыка для Яндекс Алисы на Node.js.
JavaScript
4
star
47

page-object

A Page Object pattern implementation library for JavaScript
JavaScript
4
star
48

yc-serverless-live-debug-original

Live debug of Yandex cloud functions with local code on Node.js
TypeScript
4
star
49

eslint-plugin-visual-complexity

Enforce a visual complexity of the code
JavaScript
4
star
50

npxd

Run NPX commands inside Docker container
Shell
3
star
51

fetchers

Semantic RESTful Fetch API wrappers
JavaScript
3
star
52

early-errors

A tiny script to catch webpage errors earlier.
JavaScript
3
star
53

json-micro-schema

Minimal JSON schema validation format
JavaScript
3
star
54

loggee

Zero-dependency JavaScript logger with namespaces
JavaScript
3
star
55

selenium-fileserver

Public website serving Selenium self-test static pages
JavaScript
2
star
56

alice-types

Тайпинги для протокола Алисы.
TypeScript
2
star
57

marusya-types

Тайпинги для протокола Маруси.
TypeScript
2
star
58

micro-schema

JavaScript implementation of json-micro-schema validation format
JavaScript
2
star
59

sheeva

Concurrent Automation Test Runner
JavaScript
2
star
60

subpath-imports-typescript

Example of TypeScript project with Subpath Imports
TypeScript
2
star
61

uni-skill

Универсальный интерфейс для разработки навыков голосовых ассистентов.
TypeScript
2
star
62

alice-asset-manager

Node.js API для загрузки изображений и звуков в навык Алисы.
JavaScript
2
star
63

pendings

[DEPRECATED] Better control of promises
JavaScript
2
star
64

playwright-webhook-reporter

Universal Playwright reporter to send test results to any webhook
JavaScript
1
star
65

react-server-actions-jsx

Example Next.js app with server actions returning JSX
TypeScript
1
star
66

skill-afisha-moscow

TypeScript
1
star
67

qrlink

HTML
1
star
68

promised-map

A map of promises that can be resolved or rejected by key
TypeScript
1
star
69

json-paths

Collect different paths of JSON data.
TypeScript
1
star
70

yandex-cloud-fn-internals

Roff
1
star
71

retry

Retry async function with exponential delay, timeouts and abort signals
TypeScript
1
star
72

alice-dev

Инструменты разработчика для навыков Алисы
JavaScript
1
star
73

skill-dev-proxy

Навык для Алисы, позволяющий отлаживать другие навыки прямо на устройстве
TypeScript
1
star
74

logger

Pure typescript logger with levels and prefix support
TypeScript
1
star
75

yandex-cloud-lite

Минимальный Node.js клиент для доступа к API сервисов Yandex Cloud по GRPC
JavaScript
1
star