Last active
August 29, 2015 14:26
-
-
Save cameronhunter/8550cb32130dea7a22f3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class Timer { | |
static delay(delay) { | |
return new Timer( | |
(delay ? (fn) => { setTimeout(fn, delay) } : (fn) => { fn() }), | |
(delay ? (id) => { clearTimeout(id) } : () => {}) | |
); | |
} | |
static interval(interval) { | |
return new Timer( | |
(fn) => { setInterval(fn, interval) }, | |
(id) => { clearInterval(id) } | |
); | |
} | |
constructor(start, stop, tick = () => {}) { | |
this._start = start; | |
this._stop = stop; | |
this._tick = tick; | |
} | |
timeout(duration) { | |
const start = () => { this.start() }; | |
const stop = () => { this.stop() }; | |
return Timer.delay(duration).start(start).tick(stop).stop(stop); | |
} | |
start(fn) { | |
if (fn) { | |
return new Timer((tick) => { fn(tick); return this._start(tick); }, this._stop, this._tick); | |
} else { | |
this._id = this._start(() => { this._tick() }); | |
return this; | |
} | |
} | |
stop(fn) { | |
if (fn) { | |
return new Timer(this._start, (id) => { this._stop(id); fn(id); }, this._tick); | |
} else { | |
this._stop(this._id); | |
return this; | |
} | |
} | |
tick(fn) { | |
return fn ? new Timer(this._start, this._stop, () => { this.tick(); fn(); }) : this._tick(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment