Riazbapoo
Riazbapoo

Reputation: 61

typescript - calling function at random intervals in ionic

I would like to repeatedly call the changeStyle() function at random intervals

here is my code so far:


    this.platform.ready().then(() => {
         this.myFunction()
    });
   myFunction() {
     var min = 5,
     max = 10;
     var rand = Math.floor(Math.random() * (max - min + 1) + min); //Generate Random number between 5 - 10
     this.changeStyle()
     setTimeout(this.myFunction, rand * 1000);
  }


  changeStyle() {
    console.log('changing style');
    this.sensorImage = 'path/to/image1';
    setTimeout(() => {
      this.sensorImage = 'path/to/image2';
    },
      2000);
  }

the relevant html code is

    <img id='35' (click)="changeStyle()" 
      src="{{sensorImage}}">

ideally what this should do is call the changeStyle() function repeatedly and randomly without any input from me. however, I get a runtime error saying:

'TypeError: this.changeStyle is not a function. (In 'this.changeStyle('')', 'this.changeStyle' is undefined)'

Upvotes: 0

Views: 229

Answers (2)

yashpatelyk
yashpatelyk

Reputation: 429

You could do something like this,

changeStyle() {
    ...
    ...
    const randomMilliSeconds = Math.floor( Math.random() * 10 ) * 1000;
    setTimeout(() => {
        this.changeStyle();
    }, randomMilliSeconds) 
}

You just need to call changeStyle once, manually or using click event and it will call itself at random intervals.

Upvotes: 1

gaurav soni
gaurav soni

Reputation: 206

Can you update your setTimeout(this.myFunction, rand * 1000); function to,

setTimeout(this.myFunction.bind(this), rand * 1000);

I believe the issue is related to this context.

Upvotes: 1

Related Questions