Issue:
At run time, from a system, I'm calling engine.stop() but the timer doesn't stop.
Expected behavior:
The timer and subsequently all the systems should stop.
Digging into this problem I found that this.loopId in stop() and this.loopId in loop() were exactly one apart, ie. 2047 in stop and 2048 in loop.
There's some issue with the callback passed into requestAnimationFrame. It seems to preserve the state from one iteration before, and thus, even though we set loopId to null in stop, the previous state is executed on the next call of 'loop' and loopId is reset at the end of the function.
You can see this by setting breakpoints in stop and loop and watching the loopId.
Remedy:
I added a flag called this.stopOnNextFrame. Code below:
export default class DefaultTimer {
constructor() {
this.subscribers = [];
this.loopId = null;
this.stopOnNextFrame = false;
}
loop = time => {
if (this.stopOnNextFrame ) {
this.stopOnNextFrame = false;
return;
}
if (this.loopId) {
this.subscribers.forEach(callback => {
callback(time);
});
}
this.loopId = requestAnimationFrame(this.loop);
};
start() {
if (!this.loopId) {
this.loop();
}
}
stop() {
if (this.loopId) {
this.stopOnNextFrame = true;
cancelAnimationFrame(this.loopId);
}
}
subscribe(callback) {
if (this.subscribers.indexOf(callback) === -1)
this.subscribers.push(callback);
}
unsubscribe(callback) {
this.subscribers = this.subscribers.filter(s => s !== callback)
}
}```
Issue:
At run time, from a system, I'm calling
engine.stop()but the timer doesn't stop.Expected behavior:
The timer and subsequently all the systems should stop.
Digging into this problem I found that
this.loopIdinstop()andthis.loopIdinloop()were exactly one apart, ie. 2047 instopand 2048 inloop.There's some issue with the callback passed into
requestAnimationFrame. It seems to preserve the state from one iteration before, and thus, even though we set loopId to null in stop, the previous state is executed on the next call of 'loop' and loopId is reset at the end of the function.You can see this by setting breakpoints in stop and loop and watching the loopId.
Remedy:
I added a flag called
this.stopOnNextFrame. Code below: