Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout and "this" in JavaScript

Tags:

javascript

People also ask

How do I pass this into setTimeout?

Another way we can pass arguments into the setTimeout callback is to call the function we want in the callback. Instead of trying to pass the greet function into setTimeout directly, we call greet in the callback with the arguments that we want instead. This gives us the same results as before.

What is the use of setTimeout () in JavaScript?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

What is difference between setTimeout and setInterval in JavaScript?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

What is clearTimeout in JavaScript?

The clearTimeout() method clears a timer set with the setTimeout() method.


A more elegant option is to append .bind(this) to the end of your function. E.g.:

    setTimeout(function() {
        this.foo();
    }.bind(this), 1000);
//   ^^^^^^^^^^^ <- fix context

So the answer to the OP's question could be:

    test.prototype.method = function()
    {
        //method2 returns image based on the id passed
        this.method2('useSomeElement').src = "http://www.some.url";
        timeDelay = window.setTimeout(this.method.bind(this), 5000);
        //                                       ^^^^^^^^^^^ <- fix context
    }; 

The issue is that setTimeout() causes javascript to use the global scope. Essentially, you're calling the method() class, but not from this. Instead you're just telling setTimeout to use the function method, with no particular scope.

To fix this you can wrap the function call in another function call that references the correct variables. It will look something like this:

test.protoype.method = function()
{
    var that = this;

    //method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";

    var callMethod = function()
    {
        that.method();
    }

    timeDelay = window.setTimeout(callMethod, 5000);
};

that can be this because callMethod() is within method's scope.

This problem becomes more complex when you need to pass parameters to the setTimeout method, as IE doesn't support more than two parameters to setTimeout. In that case you'll need to read up on closures.

Also, as a sidenote, you're setting yourself up for an infinite loop, since method() always calls method().


The this you used in setTimeout is scoping via itself. Create a var _this = this; inside your test.prototype.method function and use _this instead.


in es6 you can do it like this

window.setTimeout(() => {
    this.foo();
}, 1000);