faqts : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

134 of 147 people (91%) answered Yes
Recently 10 of 10 people (100%) answered Yes


How can I call setTimeout/setInterval on an object's method?
How can I call setTimeout/setInterval on an object's method?

Jan 9th, 2003 09:27
Daniel LaLiberte, Martin Honnen,

If you need to call setTimeout/setInterval on an object's method e.g. 
you want to call
  setTimeout('this.methodName()', 100)
you face the problem that a string expression for setTimeout/setInterval
is evaluated in the context of the window element and thus this is not
what you want it to be. If you have only one object, you may be able to
use a global variable to hold that object.  E.g.
  var globalObject;
  function methodName1 () {
    globalObject = this;
    setTimeout('globalObject.methodName2()', 100)
For a general solution you can maintain an array of all your objects 
which you can then index to call the right method:
function ObjectClass (property) {
  this.property = property;
  this.id = ObjectClass.cnt;
  ObjectClass.objects[ObjectClass.cnt++] = this;
  this.method = ObjectClass_method;
ObjectClass.cnt = 0;
ObjectClass.objects = new Array();
function ObjectClass_method () {
  if (confirm(this.property + ' again?'))
    setTimeout('ObjectClass.objects[' + this.id + '].method();', 100);
var obj1 = new ObjectClass('Kibo');
var obj2 = new ObjectClass('Maho');
But a far simpler solution is available since the first argument 
given to setTimout and setInterval may be a function 
instead of a string.   The function will be called with no
arguments.  Although the string or function is always evaluated in 
the global context of the window, a function may be *defined* in 
either a global or local context.  If it is defined in a local
context, such as inside another function, it has access to
local variables.  So for example.
  function ObjectClass_method () 
    var privateVar = 123;
    var timeoutFunc = function () { this.otherMethod(privateVar) };
    window.setTimeout(timeoutFunc, 100);
The timeoutFunc local variable holds the anonymous function that
references the 'this' variable from the containing method, as well
as the privateVar.  But this actually doesn't work because 
'this' is special and will be bound to something else (the window?).
You will need to store 'this' in another local variable to avoid 
confusion. By the way, the anonymous function does not have to be 
stored in a variable at all since you can just use the anonymous
function expression directly:
  function ObjectClass_method () 
    var privateVar = 123;
    var thisObj = this;
    window.setTimeout( function(){ thisObj.otherMethod(privateVar) },