0

I've been working with asynchronous functions

I've finally got around to avoid var _this = this; and switched to actually using call/apply. However when doing this,

/* inside instantiated obj */ setTimeout(function(){ /* more code here */ }.apply(this), 0); 

,does not launch an error and seems to work. Why? Because I recently noticed that it was "wrong" and should actually be:

/* inside instantiated obj */ setTimeout(function(){ /* more code here */ }.bind(this), 0); 

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

1 Answer 1

3

When you call apply or call methods on a function object, they will be invoked immediately and only the result is passed to the setTimeout.

But bind returns a new function object and that will be invoked after the timeout elapses.

Since the timeout is set to 0, both the setTimeouts wait only 0 milliseconds and so you don't see any difference.


You can use this example to understand it better.

console.log(new Date()); setTimeout(function () { console.log("Apply", new Date()); }.apply(this), 3000); setTimeout(function () { console.log("Bind", new Date()); }.bind(this), 3000); 

You should be able to observe 3 seconds difference between Bind's and the other two.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick answer. So if I understand correctly with apply/call it's not asynchronous anymore?
@Grimbode When you use apply/call they are triggered straight away.
So the function I actually want to be handled in an asynchronous way just gets invoked immediately and the setTimeout only handles the result?
@Grimbode Yes, exactly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.