npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

pinterval

v3.4.0

Published

Advanced interval

Downloads

542

Readme

pinterval

Advanced setInterval

npm version Actions Status

    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


import { Interval } from 'pinterval';

const interval = new Interval({
    func: () => console.log('Tick!'),
    time: 1000
});

interval.start();

Auto stop

If func returns false, the interval automatically stops. The following interval will stop after 10 calls.


import { Interval } from 'pinterval';
import sinon from 'sinon';

const spy = sinon.spy();
const interval = new Interval({
    func: () => {
        spy();

        return spy.calledCount < 10;
    },
    time: 1000
});

interval.start();

Error handling


import { Interval } from 'pinterval';

const interval = new Interval({
    func: () => console.log('Tick!'),
    time: 1000,
    onError: (err) => {
        if (err instanceof FatalError) {
            return false; // stop interval and terminate all further execution
        }

        return true;
    }
});

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.


import { Interval } from 'pinterval';

const interval = new Interval({
    func: () => {
        return fetch('https://github.com/trending')
    },
    time: 1000
});

interval.start();

Additionally, error handler can be asynchronous too:


import { Interval } from 'pinterval';

const interval = new Interval({
    func: () => {
        return fetch('https://github.com/trending')
    },
    time: 1000,
    onError: (err: Error) => {
        return fetch('my-service', {
            method: 'POST',
            body: JSON.stringify({
                timerError: err
            })
        })
    }
});

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:


import { Interval } from 'pinterval';

const minTimeout = 500;
const maxTimeout = 10000;
const interval = new Interval({
    func: () => console.log('Tick!'),
    time: (counter) => {
        const timeout = Math.round(minTimeout * Math.pow(2, counter));

        return Math.min(timeout, maxTimeout);
    }
});

interval.start();

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.


import { poll } from 'pinterval';

await poll(async () => {
    const result = await someProgress();

    return result === true;
}, 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.


import { until } from 'pinterval';

const data = await until(async () => {
    const result = await someProgress();

    return result.data;
}, 5000);

Times

times executes a given function a specific amount of times.


import { times } from 'pinterval';

await times(async (counter) => {
    await updateSomething(counter);
}, 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.


import { pipeline } from 'pinterval';

const out = await pipeline([() => 1, (i) => i * 2, (i) => i * 3, (i) => i * 4], 100);

console.log(out); // 24