Mar 19 2010

JS Call Later

Taki prosty skrypcik, umozliwiajacy wywolanie metody JavaScript z czasowym opoznieniem. Przydatne gdy chcemy na przyklad wyswietlic plywajacego diva 5 sekund po zaladowaniu strony, albo ukryc elementy widoku po 5 sekundach :)

Utworzmy klase obiektu dbajacego o wywolanie okreslonej metody po zadanym czasie a nastepnie sie zniszczy

loCallTimer = function(id, func, args, time)
{
	if (typeof(id) == "undefined") {
		return;
	}
	this.id = id;
	this.func = func || null;
	this.args = args || null;
	this.time = time || 1500;
	this.timer = null;
};
 
loCallTimer.prototype.suicide = function()
{
	this.stopTimer();
	eval("window.ct_" + this.id + " = null;");
};
 
loCallTimer.prototype.onTime = function()
{
	if (typeof(this.args) == "undefined" || this.args == null || this.args.length == 0) {
		this.func();
	} else {
		this.func.apply(this.func, this.args);
	}
	this.suicide();
};
 
loCallTimer.prototype.runTimer = function()
{
	this.stopTimer();
	this.timer = window.setTimeout("window.ct_" + this.id + ".onTime();", this.time);
};
 
loCallTimer.prototype.stopTimer = function()
{
	if (this.timer != null) {
		window.clearTimeout(this.timer);
		this.timer = null;
	}
};

Wyzwalacz

function callLater(func, args, time) {
    var id = (new Date()).getTime();
    var ct = eval("window.ct_" + id + " = new loCallTimer(" + id + ");");
    ct.func = func;
    ct.args = args;
    ct.time = time;
    ct.runTimer();
    return ct;
};

Testujemy

function oblicz(msg, a, b) {
	alert(msg + (a + b));
};
 
callLater(oblicz, ["Sorki, troche to trwalo ;). Suma wynosi: ", 3, 3], 3000);

Pobierz plik

Przyklad:


Zostaw odpowiedz