Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript binding using call with setInterval

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?

like image 605
d13 Avatar asked Jun 28 '12 09:06

d13


2 Answers

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

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

Should work. See .bind

like image 71
Esailija Avatar answered Nov 18 '22 13:11

Esailija


This is what I ended up with:

  var timer = {
    time: 0,
    start: function() {
      var timerTick = this.tick.bind(this);
      window.setInterval(function() {
        timerTick();
      }, 1000);
    },
    tick: function() {
      this.time += 1;
      console.log(this.time);
    }
  };

  timer.start();
like image 30
d13 Avatar answered Nov 18 '22 12:11

d13