Javascript binding using call using setInterval

How can I use a “call” with “setInterval” to get an object literal to call one of its own methods?

Here is an example. This works, and I understand why it works. The timer object calls its own tick method once per 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 using a "call". The following example is the best I've come up with. But this does not 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 really don’t understand how the call works. Can someone explain what I'm doing wrong?

Thanks!

+4
source share
2 answers

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

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

Must work. See .bind

+11
source

Here 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(); 
0
source

All Articles