2

I havethe following exported object:

module.exports = {
    value: 0,

    startTimer: function() {
        setInterval(function() {
            value++;
        }, 1000);
    }
}

How can I access value from that setInterval function? Thanks in advance.

0

1 Answer 1

2

You can either specify the full path to the value:

module.exports = {
    value: 0,

    startTimer: function() {
        setInterval(function() {
            module.exports.value++;
        }, 1000);
    }
}

Or, if you bind the function called by setTimeout to this, you can use this:

module.exports = {
    value: 0,

    startTimer: function() {
        setInterval(function() {
            this.value++;
        }.bind(this), 1000);
    }
}

This is similar to code like this, which you will see from time to time:

module.exports = {
    value: 0,

    startTimer: function() {
        var self = this;
        setInterval(function() {
            self.value++;
        }, 1000);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.