Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer returning as NaN when added

Writing some code, and when creating an instance of a class, something strange happens with an integer variable I have:

function Mat(x, y, spawner) {
    this.x = x;
    this.y = y;
    this.val = 1;
    this._spawner = spawner;
    this.newborn = true;
    this.bornTime = 0;
    this.spawnTimer = setInterval("this.bornTime++; console.log(this.bornTime);", 1000);
}

Pretty cut and clear code; every second after an instance of the variable is created, it should increment the bornTime variable by 1 and log it.

Mat.prototype.update = function() {
    if (this.bornTime >= 5) {
        this.bornTime = null;
        clearInterval(this.spawnTimer);
        this.newborn = false;
        console.log("Grown!");
    }
}

This additional code would cause this instance to be "grown" after 5 seconds, however when I check the console, it reads that bornTime is not a number(NaN).

Why is this, and is there a solution that I am not seeing?

like image 644
jatmdm Avatar asked Mar 27 '26 01:03

jatmdm


2 Answers

this inside the setTimeout code is not the same as outside (more info on MDN), so your code is actually calculating undefined++, which is NaN.

You have to create another variable, and pass a function to setTimeout instead of letting it eval a string (by the way, passing a function is supposed to be faster, and looks better):

var that = this;
this.spawnTimer = setInterval(function(){
    that.bornTime++; 
    console.log(that.bornTime);
}, 1000);
like image 113
bfavaretto Avatar answered Mar 29 '26 14:03

bfavaretto


I know this is 5 years old question but its 2018 and heres an Es6 syntax solution to avoid extra step of binding key word this.

this.spawnTimer = setInterval(() => {
    this.bornTime++; 
    console.log(this.bornTime);
}, 1000);
like image 21
Gel Avatar answered Mar 29 '26 14:03

Gel