2

I've got a Javascript object that is trying to access a local property from inside a setInterval() in a method, but apparently because it is trying to call the local scope of the function in the setInterval, the local property is returning undefined. Here's the code:

function Timer() {
    this.remaining = 15000;
}

Timer.prototype.start = function() {
this.refreshId = setInterval(function() {
    console.log(this.remaining);
},1000);
}

How can I access that local 'remaining' variable? Thanks!

J S
  • 3,324
  • 4
  • 20
  • 27

2 Answers2

2

Try this:

function Timer() {
    this.remaining = 15000;
}

Timer.prototype.start = function() {
    this.refreshId = setInterval(function(thisR) {
        console.log(thisR);
    },1000, this.remaining);
}

You can pass parameters to the setInteval function, otherwise this inside setInterval() is not your Object.

Syntax
var intervalID = window.setInterval(func, delay[, param1, param2, ...]);
var intervalID = window.setInterval(code, delay);

Source: MDN

Sergio
  • 28,539
  • 11
  • 85
  • 132
  • Your answer works, but to be totally honest this is just a bit cumbersome and it's what I was trying to avoid. Josh's answer is what I was looking for. – J S Dec 27 '13 at 22:20
  • 1
    @JS, what is best for you is best for you :) Cheers – Sergio Dec 27 '13 at 22:22
2
function Timer() {
    this.remaining = 15000;
}

Timer.prototype.start = function() {
var that = this;
this.refreshId = setInterval(function() {
    //this.adjust(-1000);
    that.remaining -= 1000;
    console.log(that.remaining);
    if (that.remaining <= 0) {
        that.remaining = 0;
        that.status = 'paused';
        clearInterval(that.refreshId);
    }
},1000);
}

setInterval functions are called in the global scope. Therefore, you can cache 'this' as a different variable (for instance, as 'that', which is common amongst developers.)

Another option is to come up with a .bind function or method, which you can find out how to do by searching Google.

Read: Understanding Javascript Closures with Ease

Josh Beam
  • 19,292
  • 3
  • 45
  • 68