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!
source share