Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables from within object into setTimeout

I'm having some interesting issues with passing in variables from within an object into setTimeout. At first, I tried putting the function I was calling from setTimeout on my object so that I wouldn't have to pass any variables into it (I was hoping it could access my object by itself). That didn't work, apparently because the function somehow became global when I called it from setTimeout, and no longer had access to my object's variables.

This was my next attempt, but it doesn't work either:

function MyObj() {
    this.foo = 10;
    this.bar = 20;
    this.duration = 1000;

    setTimeout(function(){
        AnotherFunction(this.foo, this.bar)
    }, this.duration);
}

So, how exactly can I pass in a variable into setTimeout from within an object? No, AnotherFunction won't be able to directly access MyObj for various unrelated reasons, so that's out of the question too.

like image 764
Elliot Bonneville Avatar asked May 21 '26 10:05

Elliot Bonneville


1 Answers

I think the problem is that when your function executes, this is no longer bound to MyObj. You could try

function MyObj() {
    var that = this;
    this.foo = 10;
    this.foo = 20;
    this.duration = 1000;

    setTimeout(function(){AnotherFunction(that.foo, that.bar)}, this.duration);
}

Or I do have one more idea should that not work.

like image 74
Adam Avatar answered May 23 '26 00:05

Adam