Variable scoping

This is probably totally simple, but I can’t get my head around variable scoping in this example. I need to update the value of this.progress in the below method, to output into my Progress Bar, but I get this error:

Cannot set property ‘progress’ of undefined

 function progressSimulation(count) {
      if(count < 10) {
        count++;
        this.progress = count;   //HERE IT DIES WITH THE ABOVE ERROR
        setTimeout(progressSimulation(count), (100));
      }
    }
    progressSimulation(this.progress);

THANKS A LOT!

You should use a fat arrow function to keep the scope of this.

progressSimulation(count) {
      if(count < 10) {
        count++;
        this.progress = count;   //HERE IT DIES WITH THE ABOVE ERROR
        setTimeout( () => {
        this.progressSimulation(count);
        },100);
      }
    }

something like this perhaps. But whats the reason for not using a fat arrow function in the first place?

EDIT: remove the fat arrow, use es6 function syntax

This doesn’t work for me, gives a TypeScript Error: “Expecting a ‘;’”.

maybe I’ve made a typo, I didn’t test it. But whats the reason for not using fat arrow scoping (which makes sure you keep the scope of this correct). My answer shouldn’t contain the first fat arrow btw.

It’s the same thing, just different syntax. Still scope isn’t working properly…

Off course it’s different syntax, but this scopes very different if you pass functions around. Did you declare the progress in the top of your component?

Something like this:

progress: number = 0;

Yes I did, and both ways now works, but… the delay does work. Basically the function spits out everything at once. So one thing was fixed, now there’s this new problem. I think I should do something with promises. What do you think?

Hmm it depends. Glad it’s working, but were you actually trying to achieve? Because now you set a timeout every 100ms, so it’s going to be executed superfast.

I’m trying to do a “cheat” progress bar for Firebase file upload. They only update their snapshot every 256Kb, so this doesn’t give a very smooth loading bar experience as such. That’s why I decided to do a very dirty workaround.