Menu

20 February 2009

pause in setTimeout

Hi, I have implemented a wrapper for "pausing a timed functional call using setTimeout" function in javascript. Here is the code ..

function Animator_Class(){
this.TID = null ;
this.funvar = null;
this.interval = null;
this.start_time = null;
}

Animator_Class.prototype.start_timer = function(){
this.TID = window.setTimeout(this.funvar , this.interval);
this.start_time = (new Date()).getTime();
}


Animator_Class.prototype.pause_timer = function(){
var curr_time = (new Date()).getTime();
var elapsed_time = curr_time - this.start_time ;
this.interval = this.interval - elapsed_time;
window.clearTimeout(this.TID);
}

Animator_Class.prototype.setTimeout = function(funvar, interval){
this.funvar = funvar;
this.interval = interval;
this.TID = window.setTimeout(funvar,interval);
this.start_time = (new Date()).getTime();
}
Animator_Class.prototype.clearTimeout = function(){
window.clearTimeout(this.TID);
}

Now if you want to use it in your code, use like this,,

TOB = new Animator_Class();
TOB.setTimeout('alert("OK")', 5000);

and in html forms use like,,

<input value="Pause" onclick="TOB.pause_timer()" type="button">
<input value="Start" onclick="TOB.start_timer()" type="button">


simple but important hack,,,,,,,,, :)

No comments: