0

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();
       }
    }
JJJulien
  • 269
  • 2
  • 13
  • 1
    `this` and scope are related but not the same. Functions (and sometimes blocks) created scope. What you need to know should be explained in [How to access the correct `this` inside a callback?](https://stackoverflow.com/q/20279484/218196). This might help too: https://twitter.com/fkling42/status/736228742008176640 – Felix Kling Jun 13 '18 at 18:33
  • @Felix Kling That is what I needed, thanks. And, sorry for what appears to be a dead horse. That's the problem with being new to something: not knowing the right question to ask... – JJJulien Jun 13 '18 at 18:38
  • *"not knowing the right question to ask"* yeah, that's a fundamental problem... – Felix Kling Jun 13 '18 at 18:40

0 Answers0