...

View Full Version : Using setInterval for an object's method



pushker.chaubey
06-12-2008, 03:31 PM
Hi experts,

I have defined an object's prototype named InfoObject which contains a method start() as a member method

function start(){
setInterval("this.increment()", 5000);
}

where increment() is another member method in the same InfoObject object type.

function increment(){
this.val += 10;
}


When i invoke start method on the object, I do not get intended result. increment method gets called again and again but it gived an error since "this" pointer (which refers to window object when the call is made), does not contain val field.

Here I can not use a global reference the object instead of "this" because I have defined this InfoObject in a different .js file. I include this .js file in my different html pages and create one or more instances of this InfoObject.

What I want?
Whenever I call start() on a object, it should put an invocation to
increment() method on a repeated invocation mode, so that increment() gets repeatedly called on the same object after a particular interval.

Please suggest me a way to achieve this.

Regards,
Pushker Chaubey

Arty Effem
06-13-2008, 02:06 PM
What I want?
Whenever I call start() on a object, it should put an invocation to
increment() method on a repeated invocation mode, so that increment() gets repeatedly called on the same object after a particular interval.
Try this:
function start()
{
setInterval( (function(inst){return function(){inst.increment()}})(this), 5000);
}
This is how I would use it:

InfoObject=function()
{
this.val=0;

this.start=function()
{
setInterval( (function(inst){return function(){inst.increment()}})(this), 5000);
}

this.increment=function()
{
this.val += 10;
document.title=this.val;
}

}

new InfoObject().start();

malfist
06-13-2008, 02:59 PM
That looks like a hack if I've ever seen one.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum