Last active
July 5, 2020 11:32
-
-
Save cyrusfirheir/e2537a99745c48739d3eef9893c2cb32 to your computer and use it in GitHub Desktop.
Timers with Pause/Resume/Reset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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