A resettable timer abstraction, with cancellation events. Typical usecases might include handling screen display timeouts, debouncing actions, and so on.
Calling the function exported by this module will get you a timer object, which can be started/stopped as needed. Starting an already-running timer first stops it (triggering the cancellation handler) and then starts it again.
The timeout and handlers can be defined both in the initial function call that creates the object, as well as in the arguments to the `start(...)` method.
The full API documentation can be found below the usage examples.
## Examples
A simple example:
```js
"use strict";
const timer = require("@joepie91/timer");
let someTimer = timer({
timeout: 500,
onFire: () => {
console.log("Fired 1");
},
onCancel: () => {
console.log("Cancelled 1");
}
});
someTimer.start();
/*
After 500ms:
Fired 1
*/
```
A more complex example, demonstrating resettability and cancellation handlers:
```js
"use strict";
const timer = require("@joepie91/timer");
let someTimer = timer({
timeout: 500,
onFire: () => {
console.log("Fired 1");
someTimer.start({
onFire: () => {
console.log("Fired 2");
}
});
setTimeout(() => {
someTimer.start({
timeout: 600,
onFire: () => {
console.log("Fired 3");
}
});
}, 200);
},
onCancel: () => {
console.log("Cancelled!");
}
});
someTimer.start();
/*
After 500ms:
Fired 1
200ms later:
Cancelled!
600ms later:
Fired 3
*/
```
## API
### timer(options)
Returns a new `timerObject`. The returned timer does *not* start running until you call its `start` method!