Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  111] [ 6]  / answers: 1 / hits: 17912  / 12 Years ago, thu, june 28, 2012, 12:00:00

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?


More From » binding

 Answers
3

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


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

Should work. See .bind


[#84598] Wednesday, June 27, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;