setTimeout with class method

December 26, 2009Josh Brown View Comments

There are already a few solutions floating around on how to make setTimeout or setInterval call a method in your class.  The typical solution involves a intermediate parameters and arbitrary functions.  Here is mine:

setTimeout( function(o) { o.method() }, 1000, this );

It creates an intermediate function which accepts your instance from the parameters and calls your method.  Essentially what everyone else does, but more simple.

Here is a sample script:

function MyObject()
{
	this.count = 0;
}

MyObject.prototype.tick = function( interval )
{
	this.count++;
	alert( "Tick #" + this.count.toString() +
          " every " + ( interval / 1000 ).toFixed(1) +
          " seconds!" );
}

MyObject.prototype.start = function( interval )
{
	this.timer =
          setInterval( function(o) { o.tick( interval ) }, 1000, this );
}

MyObject.prototype.stop = function()
{
	clearInterval( this.timer );
}

var it = new MyObject();
it.start( 1500 );

Here are the other solutions that I have found:

function tick( _this, interval )
{
	this = _this;
	alert( "Tick #" + this.count.toString() +
          " every " + ( interval / 1000 ).toFixed(1) +
          " seconds!" );
}

MyObject.prototype.start = function( interval )
{
	setInterval( tick, 1500, this, interval );
}

MyObject.prototype.start = function( interval )
{
	var _this = this;
	setInterval( function() { _this.tick( interval ) }, 1500 );
}

blog comments powered by Disqus