pinterval
Advanced setInterval
npm install --save pinterval
Motivation
pinterval
is a small tool that provides an advance mechanism for running an arbitrary code in intervals with flexible and simple API. It's a good fit for small badckground tasks. It supports both sync and async execution of a given function.
API
You can find API here
Features
- Support of async execution
- Graceful error handling
- Customization
Usage
Basic
; const interval = console time: 1000; intervalstart;
Auto stop
If func
returns false
, the interval automatically stops.
The following interval will stop after 10 calls.
;; const spy = sinon;const interval = { ; return spycalledCount < 10; } time: 1000; intervalstart;
Error handling
; ; interval.start;
Async
In order to pass async function, it must return a promise on each tick. Each tick is calcualated after async function completion in order to avoid race conditions.
; ; interval.start;
Additionally, error handler can be asynchronous too:
; ; interval.start;
Dynamic duration
Starting v3.3.0, you can pass a duration factory function into the consutrctor, in order to calculate dynamically interval duration for each tick:
; const minTimeout = 500;const maxTimeout = 10000;const interval = console { const timeout = Math; return Math; }; intervalstart;
The function receives a number of a tick, so you can use it to write an algorithm more accurately.
Helpers
Polling
poll
implements a simple polling mechanism.
; await poll, 5000;
Until
until
is similar to poll
but it gives you a possibility to return a value for a polling function.
The polling continues until the predicate returns anything but undefined.
; ;
Times
times
executes a given function a specific amount of times.
; await times, 5, 1000;
Pipeline
pipeline
sequentially executes a given array of functions with an interval between executions.
Each function recieves an output of a previous one.
NOTE: Unlike other functions, pipeline
executes a first function with 0 timeout time, which means the provided timeout value is used between executions only.
If you want to override this behavior, you must provide a function that calculates timeouts.
; ; console.logout; // 24