Does anyone know why this method is returning NaN?

let count= {
amount: 0,
count: function(){
this.amount++
console.log(this.amount);
},
start: function(num){
setInterval(this.count,num)
}
}

if i were to run count.start(500); it would return not a number

I think it’s because when setInterval invokes this.count, it’s not invoking it in the context of the count object (i.e., it’s not called the same way as count.count(), in which case this.amount means the amount property in your object), but rather it’s called in the context of the global object. In this case this.amount means the amount variable in the global scope (which doesn’t exist). Try adding var amount = 10; before calling .start to see what I mean.

If you want to make it work the way you intended is to pass this.count.bind(this) to setInterval.

1 Like