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!

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Absolutely, no problem.
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

2 Comments

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.
@JS, what is best for you is best for you :) Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.