Reputation: 548
Why can't we do call and apply on setTimeout,
var obj={}
window.setTimeout.call(obj,callback,delay);//it throws error stating illegal invocation
Upvotes: 3
Views: 3080
Reputation: 65815
It makes no sense to use .call
on setTimeout
since .call
is meant to invoke a function and supply context to that function when it is invoked. In other words, you're not trying to invoke setTimeout with context supplied to it, you're trying to invoke the callback with context supplied to it.
To accomplish this with setTimeout
, you'd use .bind, as in:
var obj={};
window.setTimeout(callback.bind(obj),delay);
Upvotes: 3
Reputation: 12027
From the WHATWG setTimeout documentation:
The setTimeout() method must return the value returned by the timer initialisation steps, passing them the method's arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to false.
setTimeout
needs to be called from the context of the window
object. The context passed into the .call
method is not the window object. To call setTimeout
correctly, do:
setTimeout.call(window, callback, delay);
Upvotes: 2