Skip to content

Lightweight and easy-to-use library bringing JavaScript-style timers into .NET with no dependencies, built on .NET standard 2.0

License

Notifications You must be signed in to change notification settings

2chevskii/JsTimers

Repository files navigation

Project logo

Codefactor stats AppVeyor build status AppVeyor build status

JavaScript-style timers for .NET

Library offers simple API which mimics behaviour of NodeJS/Browser functions available in JavaScript, such as

  • SetTimeout
  • SetInterval
  • SetImmediate
  • ClearTimeout
  • ClearInterval
  • ClearImmediate

Original behaviour is closer to NodeJS (Returns objects instead of numbers, has ability to keep application running, et cetera) and is replicated as much as possible inside of the CLR

Documentation

For the full guide on the package functionality, make sure to check out the docs

Installation

Package manager console

Install-Package JsTimers

.NET CLI

dotnet add package JsTimers

Usage

All methods of library's public API are located inside JsTimers.TimerManager therefore, explanations below will not contain this type as prefix to presented method

For most cases it is easier to include using static directive in your code as shown below:

using static JsTimers.TimerManager;

Simple timer

To create basic timer, which will be fired once after specified delay, use SetTimeout method:

SetTimeout(() => {
  Console.WriteLine("Hello, JsTimers!");
}, 1000);

This will issue a timeout of 1 second and then execute a given callback

Cancelling timers

All methods mentioned above actually return objects which represent timers. These objects could be assigned to a variable for further actions, such as cancelling:

Timeout timeout = SetTimeout(() => {
  Console.WriteLine("This callback will not fire");
}, 1000);
ClearTimeout(timeout);

Important

Do not use this library to time execution of actions which require very high precision. Library runs internal loop and processes all active timers one by one, this might sometimes cause overhead of up to 30ms, therefore it works fine in most cases when you build general purpose software, but if you want to build an atomic clock with that, I have bad news for you