splunk splunk - 2 months ago 17
TypeScript Question

Typescript function returns NaN value but number type

I have this countdown timer function:

startTimer(duration) {
this.myTimer = duration;
setInterval(function () {
this.myTimer--;
console.log("TIMER: "+ typeof(this.myTimer) + " "+this.myTimer);
}, 1000);
}


which I call in this way:
this.startTimer(60);


This is the result of
console.log
:
TIMER: number NaN
.
So
typeof(this.myTimer)
returns
number
type and when I print its value I get
NaN
.

Why do I get
NaN
?

Note: I'm using Angular2 (typescript) and I've defined
myTimer
variable inside the component class right before the constructor in this simple way:

export class myComponent {
myTimer;
constructor(private navCtrl: NavController) {}
// my code (previous function is here)
}

Answer

Like Rayon said in the comments, in your setTimeout function callback you have another this than in your startTimer function, so myTimer isn't a member of it. undefined becomes NaN after the -- operation.

To fix it you can either use the var that = this; thing or use an arrow function:

function startTimer(duration) {
    this.myTimer = duration;
    setInterval(() => {
        this.myTimer--;
        console.log("TIMER: "+ typeof(this.myTimer) + " "+this.myTimer);
    }, 1000);
}
Comments