PDA

View Full Version : setTimout



claudio
April 28th, 2005, 02:33 PM
It's basically a setInterval with no worries of cleaning the interval, as it executes the function or instruction only once.
// Executes a function or instruction after a
// number of milisseconds and then clears the call.
_global.setTimeout = function() {
if (arguments[0] instanceof Function) {
this.obj = null;
this.method = arguments[0];
this.interval = arguments[1];
this.args = arguments[2] instanceof Array ? arguments[2] : [arguments[2]];
} else if (typeof (arguments[0]) == "object" || typeof (arguments[0]) == "movieclip") {
this.obj = arguments[0];
this.method = eval(arguments[1]);
this.interval = arguments[2];
this.args = arguments[3] instanceof Array ? arguments[3] : [arguments[3]];
}
this.$function = function() {
this.method.apply(this.obj, this.args);
clearInterval(this.$interval);
};
this.$interval = setInterval(this, "$function", this.interval);
};
setTimeout.prototype.clearTimeout = function() {
clearInterval(this.interval);
};
// Usage is similar to setInterval, except that if more than
// one parameter is passed, it must be passed as an Array.
//
// setTimeout(functionName,interval [,param1,param2,...,paramN])
// or
// setTimeout(obj,"functionName",interval [,param1,param2,...,paramN])
//
// Examples:
var name = "claudio";
function Test(msg) {
trace("My name is "+msg);
}
function Sum(a, b) {
trace("Result = "+(a+b));
}
// executes the Scream function after 3000 milisseconds passing the variable "name" as a parameter
var a = new setTimeout(Test, 2000, name);
// tell the movieclip square to gotoAndStop frame "end" after 4000 milisseconds
var b = new setTimeout(square, "gotoAndStop", 3000, "fim");
// cancel the timeout call above
b.clearTimeout();
// executes the Sum function after 4000 milisseconds passing the values "10" and "5" as parameters
var b = new setTimeout(Sum, 4000, [10, 5]);

senocular
April 28th, 2005, 02:37 PM
a version is also available in the setInterval tutorial on kirupa.com ;)
... well, here it is for comparison :)


_global.setTimeout = function(a,b,c, args){

// for a basic function call:
if (typeof a == "function"){

args = arguments.slice(2);
var ID, func = function(){

a.apply(null, args);
clearInterval(ID);

}
ID = setInterval(func, b, args);

// for an object method call:
}else{

args = arguments.slice(3);
var ID, func = function(){

a[b].apply(a, args);
clearInterval(ID);

}
ID = setInterval(func, c, args);

}
return ID;

}
_global.clearTimeout = clearInterval;


Usage is same as setInterval.

claudio
April 28th, 2005, 02:43 PM
Ahhh i didnt know about the tutorial :P

stringy
July 12th, 2005, 07:10 PM
This has been one of the most useful threads i have ever read on Kirupa. Nice stuff guys.