@yr/clock
v2.1.0
Published
A global timer utility for managing immediate/timeout intervals
Readme
A universal (Node.js or browser), global timer utility for managing immediate/timeout intervals:
- uses
requestAnimationFramefor short timeout intervals (under 1000ms) - uses
process.nextTickorPromise.resolveto schedule "immediate" calls - enables/disables all timers when browser window no longer active (via
visibilityapi)
Usage
const clock = require('@yr/clock');
clock.timeout(100, () => {
// Do something
});API
init(features): initialize enabling/disabling all timers on window visibility change. features is an object containing the following:
hidden: string value for current browser's (potentially vendor prefixed)document.hiddenproperty (ex:"webkitHidden")visibilityChange: string value for current browser's (potentially vendor prefixed)window.visibilitychangeevent property (ex:"webkitvisibilitychange")
Timers which expire while disabled will fire as soon as the window is enabled.
immediate(fn, ...args): trigger fn as soon as possible after the current turn of the event loop. Uses process.nextTick where available (Node.js), otherwise Promise.resolve (may require Promise polyfill on some clients).
clock.immediate(() => {
// Do something
});frame(fn): trigger fn on next animation frame (or short setTimeout if requestAnimationFrame is not supported). Returns an id to use for cancelling.
clock.frame(() => {
// Do something
});timeout(duration, fn, id, ...args): trigger fn after duration (in milliseconds). Returns an id to use for cancelling. Optionally pass an id string to manually assign an id. This will have the effect of automatically cancelling an existing timeout with the same id.
clock.timeout(100, () => {
// Do something
}, 'myTimer');cancel(id): cancel running frame or timeout interval.
const handle = clock.timeout(100, () => {
// Nope
});
clock.cancel(handle);