Skip to content

Instantly share code, notes, and snippets.

@gnandretta
Created April 27, 2021 00:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnandretta/347e146da39e240c8707b3aabf148849 to your computer and use it in GitHub Desktop.
Save gnandretta/347e146da39e240c8707b3aabf148849 to your computer and use it in GitHub Desktop.
class Looper {
constructor(opts) {
this.video = $("video");
this.loop(opts);
}
loop(opts = {}) {
clearTimeout(this.loopTimeoutId);
this.setOpts(opts);
this.video.playbackRate = this.playbackRate;
this.video.currentTime = this.start;
this.video.play();
const duration = (this.end - this.start) * 1000 / this.playbackRate;
this.loopTimeoutId = setTimeout(() => this.loop(), duration);
}
stop() {
clearTimeout(this.loopTimeoutId);
this.video.pause();
}
setOpts(opts) {
const isNumber = (x) => typeof x === "number";
if (isNumber(opts.start)) {
this.start = opts.start;
} else if (!isNumber(this.start)) {
throw new Error('missing start');
}
if (isNumber(opts.end)) {
this.end = opts.end;
} else if (!isNumber(this.end)) {
throw new Error('missing end');
}
if (isNumber(opts.playbackRate)) {
this.playbackRate = opts.playbackRate;
} else if (!isNumber(this.playbackRate)) {
this.playbackRate = 1;
}
}
}
// example
const looper = new Looper({ start: 0, end: 17, playbackRate: 0.7 })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment