Skip to content

Instantly share code, notes, and snippets.

@cyrusfirheir
Last active July 5, 2020 11:32
Show Gist options
  • Save cyrusfirheir/e2537a99745c48739d3eef9893c2cb32 to your computer and use it in GitHub Desktop.
Save cyrusfirheir/e2537a99745c48739d3eef9893c2cb32 to your computer and use it in GitHub Desktop.
Timers with Pause/Resume/Reset
window.Timer = function(callback, duration = 500) {
if (!callback) return;
this.callback = callback;
this.duration = duration;
this.remaining = duration;
this.resume();
};
Timer.prototype.resume = function() {
this.start = new Date();
this.timerId = setTimeout(this.callback, this.remaining);
};
Timer.prototype.pause = function() {
window.clearTimeout(this.timerId);
delete this.timerId;
this.remaining -= new Date() - this.start;
};
Timer.prototype.reset = function() {
this.pause();
this.remaining = this.duration;
};
Timer.prototype.clone = function () {
return new Timer(this);
};
Timer.prototype.toJSON = function () {
var ownData = {};
Object.keys(this).forEach(function (pn) {
ownData[pn] = clone(this[pn]);
}, this);
return JSON.reviveWrapper('new Timer($ReviveData$)', ownData);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment