Repeat function every so often, so many time and refresh page

I would like a function to be called every so many milliseconds but only for so many times.
Using setTimeout(() => { does not seem to update the screen or scope.
In Ionic1 there was a scope.apply method.

What is the best way to achieve this in Ionic2?

I’d suggest looking to rxjs Observables for this.

P

My problem was that I was trying to access a variable to ‘this’ from inside the setInterval ( and setTimeout) function.
By creating a reference to ‘this’, changes to the variable, within the setInterval loop, affected my display.

This example rolls a pair of dice, changing the images every 100 ms:

 rollDice() {
        var t_this = this;
        var i = 0
        var roll_int = setInterval(function () {
          t_this.die1 = Math.floor((Math.random() * 6) + 1);
          t_this.die2 = Math.floor((Math.random() * 6) + 1);
          i++;
          if (i > 12) {
            clearInterval(roll_int);
            t_this.rolling = false;
          }
        }, 100);
      }

This is why fat arrow functions exist.

You’re right - I just tried it and it worked.

So, to wrap up… referencing this.die1 works if I use:

var roll_int = setInterval(() => {

And using a variable to count the loops and clearing the interval when done, while may not be elegant, worked.

I think you can probably do this somewhat more cleanly using Observables. Something like:

Observable.interval(100).take(12).subscribe(() => {
  this.die1 = Math.floor((Math.random() * 6) + 1);
  this.die2 = Math.floor((Math.random() * 6) + 1);
});

That does work but how would you fire a function off at the end?

With a third argument to subscribe:

subscribe(() => { do stuff }, (err) => { shouldn't happen }, () => { we're done });

Yup, works like a charm
Thank you rapropos and thank you PWHSoftware!
Learned a lot here.