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

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

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”

Jason
Guest

I don’t know ionic but I think you should use arrow function/fat arrow as shown below,

this.stop = setInterval(()=> {
        console.log(this.clickCount); //this will log this.clickCount
    }, 1000);
}

You can check this answer with arrow function and without arrow function. But no Ionic. sorry for that.