Skip to content

Instantly share code, notes, and snippets.

@cameronhunter
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronhunter/8550cb32130dea7a22f3 to your computer and use it in GitHub Desktop.
Save cameronhunter/8550cb32130dea7a22f3 to your computer and use it in GitHub Desktop.
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