Javascript binding using call with setInterval

d13 picture d13 · Jun 28, 2012 · Viewed 11.9k times · Source

How can I use "call" with "setInterval" to get an object literal to invoke one of its own methods?

Here's an example. This works, and I understand why it works. The timer object calls its own tick method once each second

var timer =
{ 
  start: function()
  {
    var self = this;
    setInterval(function(){self.tick();}, 1000);

  },

  tick: function()
  {
    console.log("tick!");
  }
};

timer.start();

I tried to simplify this code by using "call". This next example is the best that I came up with. But it doesn't work: the tick method is called only once, and then I get a type error.

var timer =
{ 
  start: function()
  {
    setTimeout.call(this, this.tick(), 1000);
  },

  tick: function()
  {
    console.log("tick!");
  }
};

timer.start();

I think I don't really understand how call works. Can anyone explain what I'm doing wrong?

Answer

Esailija picture Esailija · Jun 28, 2012

You are .calling .setInterval not your callback function which the browser calls:

setInterval( this.tick.bind(this), 1000 );

Should work. See .bind