Well this could seem redundant given the numerous topic about interaction between Promises and setTimeout but I can't find an answer that exactly fit my case (or that I am capable of interpreting !)
In the case of a Video player API usage, I need to loop on a sequence, and exit the loop when a certain condition is reached.
The following code works, but I was wondering if there was a sexier way, using Promise chaining instead of this :
export class LoopStep {
// looping from 0 to 5 seconds in the video
this.duration = 5;
this.start = 0;
onStart() { // entry point
return this.onLoop();
}
onLoop() {
return new Promise((resolve) => {
this.loopAndResolve(resolve);
});
}
loopAndResolve(resolve) { // start loop
if(this.isLooping) { // exit condition when turned to false
this.player.setTime(this.start);
this.player.play();
setTimeout(this.loopAndResolve.bind(this, resolve), this.duration * 1000); // callback
} else {
resolve();
}
}
}
// Anywhere else
loopStep.onStart.then(()=> console.log('exiting loop successfully')); // OK
Actually I would find more appropriated to avoid passing the "resolve" function as a parameter (only because I have a feeling that this could be wrong, or at least not "the most efficient/sexy").
resolve
. \$\endgroup\$