Sunday, November 9, 2008

Timer in javascript

There can be certain requirements where we need to call a function using java script after specific time instants like (Thread.Sleep(Time in Milli seconds)).

since java script does not support Threads at back ground , but indirectly can replicate the functionality of Thread.Sleep with javascript function (setTimout) which shall call a function after every specific time mentioned as parameter to this function.
Example :-
var cnt=0;
function test()
{
cnt++;
alert(cnt);
}
var tmr=setTimout("test();",2000);


In the above case we can see test is a javascript function which is when called increments the cnt variable and displays an alert box that displays the value of the variable cnt.
Also i have declared a timer variable that refers to timer function that calls this test function for every 2000 milli seconds or 2 seconds.
We need not require to bother for calling the function for every 2 seconds once this timer function is assigned or called.

To reset or of the timer function we say clearTimeout(tmr);

No comments: