How does scope change during recursion in the following code?
Specifically, the first call to _action()
, works intuitively and maintains references to this._updateRateMilliseconds
and this._updateAction
. However, during the second entry via recursion they are lost.
The code works with the following change:
setTimeout(this._action, this._updateRateMilliseconds);
--> setTimeout(this._action.bind(this), this._updateRateMilliseconds)
.
Could someone please explain how the scope changed during recursion and why I need the confusing, at least to me, this._action.bind(this)
?
export class UpdateTimer {
constructor(updateRateMilliseconds, updateAction) {
this._updateRateMilliseconds = updateRateMilliseconds;
this._updateAction = updateAction;
this._stopUpdates = true;
}
_action() {
if (this._stopUpdates) return;
this._updateAction();
setTimeout(this._action, this._updateRateMilliseconds);
}
Stop() {
this._stopUpdates = true;
}
Start() {
this._stopUpdates = false;
this._action();
}
}