[SOLVED] This inside a timeout

Can someone explain why we can’t use this inside a timeout directly?

    var that = this;
    setTimeout(function(){
        that.stone.reparent(this.entity);
        that.stone.enabled = false;
    }, 1000);

The context of this inside the timeout callback is that of the anonymous function().

You should be using either your that variable or use bind to change the context, like this:

    setTimeout(function(){
        that.stone.reparent(this.entity);
        that.stone.enabled = false;
    }.bind(this), 1000);

That isn’t specific to Playcanvas but in general how Javascript functions.

After I have posted this question I see that I have forgotten a this, and that is why it is so annoying.

that.stone.reparent(this.entity);

Do I understand correctly that i can use

setTimeout(function(){
    this.stone.reparent(this.entity);
    this.stone.enabled = false;
}.bind(this), 1000);

instead of

var that = this;
setTimeout(function(){
    that.stone.reparent(that.entity);
    that.stone.enabled = false;
}, 1000);

Yes, exactly!

You can use either. In the past using bind had a small performance hit, but from what I know browsers now have improved.

I find bind a bit easier to read when structuring my code. In the Playcanvas engine source code you will find mostly your that (or self as usually used) solution.

Yes it is a lot of easier indeed! I don’t have to change every this inside a timeout, so thanks for this solution!
(PS. I don’t know how to change a topic to solved).

1 Like

Try the pencil by the side of the topic subject:

image

If that doesn’t work, an admin will do that at some point.

I only can change the title and category.

I am 99% sure what admins do is prepend [SOLVED] to the title.

Are u kidding me? I can do that by myself haha!

Thanks for your help @Leonidas !

1 Like

Παρακαλώ (you are welcome) @Albertos! :innocent:

1 Like