shelving
Version:
Toolkit for using data in JavaScript.
47 lines (46 loc) • 1.31 kB
JavaScript
/**
* Create a new Timeout.
*
* Wrapper for `setTimeout()` that...
* - Keeps track of the reference returned from `setTimeout()`
* - Clears the any existing timeout when a new timeout is set.
* - Allows a default delay to be set that is applied to all new timeouts that don't have a delay set.
*
* @param ms The default delay for any created timeouts (in ms).
*/
export class Timeout {
_callback;
_ms;
_timeout = undefined;
constructor(callback = undefined, ms = 0) {
this._callback = callback;
this._ms = ms;
}
/** Is a timeout currently set? */
get exists() {
return !!this._timeout;
}
/**
* Cancel any existing timeout and set a new one.
* @param callback
* @param ms The delay for this timeout (in ms).
*/
set(callback = this._callback, ms = this._ms) {
this.clear();
if (callback)
this._timeout = setTimeout(_executeTimeout, ms, this, callback);
}
/** Cancel any existing timeout.. */
clear() {
const timeout = this._timeout;
if (timeout) {
this._timeout = undefined;
clearTimeout(timeout);
}
}
}
/** Actually execute the timeout. */
function _executeTimeout(timeout, callback) {
timeout.clear();
callback();
}