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
For the full guide on the package functionality, make sure to check out the docs
Install-Package JsTimers
dotnet add package JsTimers
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;
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
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);
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