Sometimes I use the following concept:
class ResetableTimeout extends EventEmitter {
constructor() {
this.id = -1;
}
start(delay) {
clearTimeout(this.id);
this.id = setTimeout(() =>{this.emit("done");}, delay);
}
}
Architecture like this may be used for throttling operations for example.
Now I noticed that this may fire twice under these circumstances:
setTimeoutstarts timeoutstart(delay)is called and is executing- Timeout fires and the callback is pushed in the eventloop, waiting for
start(delay)to end clearTimeoutis called, but the timeout is done alreadystart(delay)ends and timeout's callback executesdelayms later, timeout's callback executes again
Is this possible? If it is possible how to prevent it? If it isn't possible, what prevents it from happening?