Last Updated: February 25, 2016
·
13.36K
· francisc

Set callback context for setTimeout() and setInterval()

By default, the context (this) for window.setTimeout() callbacks is set to the global object (window in browsers).

When working with classes, you sometimes need to keep the context to be that of the class instance. You can achieve this using the bind() method to explicitly set the context.

function UselessDelay()
{
    this.message='Why was I delayed?';
}

UselessDelay.prototype.start=function()
{
    window.setTimeout(this.show.bind(this),1000);
}

UselessDelay.prototype.show=function()
{
    console.log(this.message);
};

Usage

var ud=new UselessDelay();
ud.start();//Will show 'Why was I delayed?' after 1 second

3 Responses
Add your response

As Function#bind isn't that fast, I'd rather use a simple Function#call here.

UselessDelay.prototype.start = function(){
  var self = this
  window.setTimeout(function(){
    self.show.call(self)
  }, 1000)
}
over 1 year ago ·

That's true. According to jsPerf it's 90% slower which is significant.

Good comment.

over 1 year ago ·

Hm, it actually depends a lot on the browser. Bind is much faster (~80%) on IE and Opera, latest versions of both. But slower on Chrome and Firefox, also latest versions.

over 1 year ago ·