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

tasktimer

v3.0.0

Published

An accurate timer utility for running periodic tasks on the given interval ticks or dates. (Node and Browser)

Downloads

17,543

Readme

An accurate timer utility for running periodic tasks on the given interval ticks or dates.

Why TaskTimer?

Because of the single-threaded, asynchronous nature of JavaScript, each execution takes a piece of CPU time, and the time they have to wait will vary, depending on the load. This creates a latency and cumulative difference in asynchronous timers; that gradually increase the inacuraccy. TaskTimer claims to be the best timer that overcomes this problem as much as possible.

Secondly, I needed a task manager that can handle multiple tasks on different intervals, with a single timer instance.

Features

  • Precission & Accuracy: With the precision option (enabled by default);
    • The delay between each tick is auto-adjusted when it's off due to task/CPU loads or clock drifts.
    • In Node.js, TaskTimer also makes use of process.hrtime() high-resolution real-time. The time is relative to an arbitrary time in the past (not related to the time of day) and therefore not subject to clock drifts.
    • The timer may hit a synchronous / blocking task; or detect significant time drift (longer than the base interval) due to JS event queue, which cannot be recovered by simply adjusting the next delay. In this case, right from the next tick onward; it will auto-recover as much as possible by running "immediate" tasks until it reaches the proper time vs tick/run balance.
  • Run or schedule multiple tasks (on a single timer instance).
  • Ability to run sync or async tasks that return a promise (or use callbacks).
  • Ability to balance task-loads via distributing executions by tick intervals.
  • Ability to limit total runs of a task.
  • Stateful tasks: i.e. ability to auto-stop when all tasks complete.
  • TaskTimer is also an EventEmitter.
  • Universal module. Works in both Node and Browser.
  • Small size (4.5kB minified, gzipped).
  • Completely re-written in TypeScript. (version 2.0.0+)

Installation

npm i tasktimer

Usage

In Node/CommonJS environments:

const { TaskTimer } = require('tasktimer');

With transpilers (TypeScript, Babel):

import { TaskTimer } from 'tasktimer';

In (Modern) Browsers:

<script src="js/tasktimer.min.js"></script>
<script>
    const { TaskTimer } = tasktimer;
</script>

Simplest Example

const timer = new TaskTimer(1000);
timer.add(task => console.log(`Current runs: ${task.currentRuns}`)).start();

Regular Timer (without Task Management)

const timer = new TaskTimer(5000);
timer.on('tick', () => console.log(`Tick count: ${timer.tickCount}`));
timer.start();

Detailed Example

// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// interval can be updated anytime by setting the `timer.interval` property.

// Add multiple tasks (at once) based on tick intervals.
timer.add([
    {
        id: 'task-1',       // unique ID of the task
        tickInterval: 5,    // run every 5 ticks (5 x interval = 5000 ms)
        totalRuns: 10,      // run 10 times only. (set to 0 for unlimited times)
        callback(task) {
            // code to be executed on each run
            console.log(`${task.id} task has run ${task.currentRuns} times.`);
        }
    },
    {
        id: 'task-2',       // unique ID of the task
        tickDelay: 1,       // 1 tick delay before first run
        tickInterval: 10,   // run every 10 ticks (10 x interval = 10000 ms)
        totalRuns: 2,       // run 2 times only. (set to 0 for unlimited times)
        callback(task) {
            // code to be executed on each run
            console.log(`${task.id} task has run ${task.currentRuns} times.`);
        }
    }
]);

// You can also execute some code on each tick... (every 1000 ms)
timer.on('tick', () => {
    console.log('tick count: ' + timer.tickCount);
    console.log('elapsed time: ' + timer.time.elapsed + ' ms.');
    // stop timer (and all tasks) after 1 hour
    if (timer.tickCount >= 3600000) timer.stop();
});

// Start the timer
timer.start();

How it works

  • When you create a timer; you set a time-interval (e.g. 1000 milliseconds), to be used as base resolution (tick) for the tasks.
  • Then add task(s) to be executed on tick-intervals.
    (e.g. task1 runs on every 10th tick, task2 runs on every 30th)
  • You can optionally define:
    • The number of total runs,
    • An initial delay,
    • Start/end dates for each task...
  • In addition to task callbacks; event listeners can be added to execute some other code on each tick (base interval) or task run, etc...
  • You can add, remove, reset, disable individual tasks at any time, without having to stop or re-create the timer.
  • Pause and resume the timer at any time; which effects all current tasks.

Documentation

See API reference and examples here.

Changelog

See CHANGELOG.md.
If you're migrating from TaskTimer v1 to v2+, there are various breaking changes!..

Contributing

Clone original project:

git clone https://github.com/onury/tasktimer.git

Install dependencies:

npm install

Add tests into test/node and test/browser and run:

npm run test!   # builds and runs tests
npm test        # runs tests without building

Use included tslint.json and editorconfig for style and linting.
Travis build should pass, coverage should not degrade.

License

MIT.