• Stars
    star
    428
  • Rank 97,982 (Top 2 %)
  • Language
    JavaScript
  • Created over 6 years ago
  • Updated over 3 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,915
star
3

github-trending-repos

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

angular-xeditable

Edit in place for AngularJS
HTML
1,915
star
5

checklist-model

AngularJS directive for list of checkboxes
HTML
1,053
star
6

awesome-smart-tv

⚡A curated list of awesome resources for building Smart TV apps
1,019
star
7

websocket-as-promised

A Promise-based API for WebSockets
JavaScript
571
star
8

bootstrap-editable

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

combodate

Dropdown date and time picker
JavaScript
208
star
10

playwright-bdd

BDD testing with Playwright runner
TypeScript
195
star
11

autotester

Chrome extension that allows to develop and run automation tests right in browser
JavaScript
169
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
125
star
14

babel-plugin-runtyper

⚡️ Runtime type-checker for JavaScript
JavaScript
117
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
82
star
17

bro-fs

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

tinkoff-invest-api

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

yii-bootstrap-editable

Yii extension for Bootstrap-editable plugin
JavaScript
31
star
20

alice-renderer

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

alice-workshop

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

js-testrunners-bench

JavaScript test-runners benchmark
JavaScript
27
star
23

groupgridview

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

lazy-model

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

chnl

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

tinkoff-robot

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

playwright-bdd-example

Example project that uses playwright-bdd to run BDD tests
TypeScript
19
star
28

docker-stack-wait-deploy

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

alice-tester

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

promise-controller

Advanced control of JavaScript promises
JavaScript
13
star
31

controlled-promise

Advanced control of JavaScript promises
JavaScript
13
star
32

mocha-es6-modules

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

yandex-cloud-deploy-fn

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

tinkoff-local-broker

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

alice-cloud-proxy

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

ydb-sdk-lite

Lightweight implementation of Yandex Database SDK for Node.js
JavaScript
5
star
37

throw-utils

Helpers for error throwing
TypeScript
5
star
38

wait-for-cmd

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

selgridview

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

alice-protocol

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

alice-skill-starter

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

flat-options

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

yandex-cloud-fn

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

alice-testing-example

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

page-object

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

fetchers

Semantic RESTful Fetch API wrappers
JavaScript
3
star
47

early-errors

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

json-micro-schema

Minimal JSON schema validation format
JavaScript
3
star
49

loggee

Zero-dependency JavaScript logger with namespaces
JavaScript
3
star
50

yc-serverless-live-debug-original

Live debug of Yandex cloud functions with local code on Node.js
TypeScript
3
star
51

npxd

Run NPX commands inside Docker container
Shell
2
star
52

selenium-fileserver

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

alice-types

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

marusya-types

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

micro-schema

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

sheeva

Concurrent Automation Test Runner
JavaScript
2
star
57

uni-skill

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

alice-asset-manager

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

pendings

[DEPRECATED] Better control of promises
JavaScript
2
star
60

skill-afisha-moscow

TypeScript
1
star
61

qrlink

HTML
1
star
62

yandex-cloud-fn-internals

Roff
1
star
63

retry

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

alice-dev

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

promised-map

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

logger

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

skill-dev-proxy

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

yandex-cloud-lite

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