Jinu Joseph Daniel
Jinu Joseph Daniel

Reputation: 6291

Javascript SetInterval() scope problem

I wrote a class in javascript that looks like this:

function main()
{
    this.var1 =0;
    this.clock = function()
    {
        var t = this;
        var n =1;
        window.setInterval(document.write(this.n++),1000);
    }
}

But after calling setInterval() 'this' refers to window. So i cannot access the variable inside the class. How can I solve this scope problem?

Upvotes: 3

Views: 8355

Answers (4)

Marata
Marata

Reputation: 11

function main()
{
    this.var1 =0;
    this.clock = function()
    {
        var t = this;
        var n = 1;
        window.setInterval(function(){ document.write( t.n++); },1000);
    }
}

You already declared t, use it! All guys are correct, use the function statement, but to mantain n in the scope use t.

Upvotes: 1

user578895
user578895

Reputation:

First of all, your setInterval isn't doing what you think. You're doing a setInterval on the result of document.write(this.n++). The write happens immediately and will only ever fire once.

Code should be:

setInterval(function(){
    document.write(n++);
}, 1000);

setInterval takes a function to execute every n ms. The scope of the function has access to your n variable, so you don't need a this

Upvotes: 3

Marc B
Marc B

Reputation: 360602

document.write.... now that's old school. Try document.write(main.n++) instead?

Upvotes: 0

Jakub Konecki
Jakub Konecki

Reputation: 46008

function main()
{
    this.var1 =0;
    this.clock = function()
    {
        var t = this;
        var n = 1;
        window.setInterval(function(){ document.write(n++); },1000);
    }
}

Notice that your code is wrapped in function.

Upvotes: 6

Related Questions