Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic2 function setInterval can't get a parameter

I use Ionic2 to build an app,which based on Angular2 and Cordova. when I use function setInterval to get a parameter called clickCount,it occurt an undefine error.

export class ItemDetailsPage {
static get parameters() {
    return [[NavController], [NavParams]];
}
constructor(nav, navParams) {
    this.nav = nav;
    this.clickCount = 0;
    this.selectedItem = navParams.get('item');
}

startTapped(event) {
   var cp= this.clickCount;   //here can get the clickCount
    this.stop = setInterval(function() {
        console.log(this.clickCount); //occur a undefined error
    }, 1000);
}

}

the error

like image 650
Jonathan Zhao Avatar asked Dec 09 '25 16:12

Jonathan Zhao


1 Answers

it is a scope problem, to solve it quickly, just do it:

startTapped(event) {
   var that = this;
   this.stop = setInterval(function() {
       console.log(that.clickCount); //no more undefined error
   }, 1000);
}

I happens because "this" inside the "setInterval" is the function "setInterval" it self, not the "this" of the scope of "startTapped", if you create a pointer to the "this", you can use that pointer inside "setInterval"

like image 123
Adriano Spadoni Avatar answered Dec 11 '25 05:12

Adriano Spadoni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!