Pages

Sunday, June 17, 2012

timing events in javascript

setInterval() and setTimeout()

are the two methods available in javascript which we can use to invoke timing events.
setInterval() method takes two arguments,first one is the name of the function to be called after the time interval that we have provided as argument to the setInterval() method of ours.
and Second argument is the time interval itself in milliseconds.
i.e setInterval(functionName(),1000);
It will keep on calling functionName() after every 1000 milliseconds
We can stop this repeated calling of function explicitaly using another javascript method that is
clearInterval(intervalvar)
where intervalvar is variable for setInterval()
 var intervalvar=setInterval("function name",1000);

here is an interesting example using setInterval() to implement a slideshow of images:

<html>
<head>
<title>changing Image</title>
<script type="text/javascript">
 var images= new Array();
 images[0]="image1.jpg";
 images[1]="image2.jpg";
 images[2]="image3.jpg";
 images[3]="image4.jpg";
 images[4]="image.jpg";
 var x=0;
function timer()
{
    setInterval(function() {slider()},7000);
}
function slider()
{
 document.getElementById("slide").src=images[x];
 if(x<4)
 {
     x=x+1;
   
 }
 else
 {
     x=0;
 }
}
</script>
</head>
<body onload="timer()">

<image id="slide" src="image.jpg" style="border-style:solid; border-width:5px; border-color:green;" width="500" height="400"/>

</body>
</html>

setTimeout() is another timing event method,it also accept two arguments function to be called after timeout and time period.
i.e setTimeout(function(),3000);
It will call function() after 3000 milli seconds,but only once ! !

example for setTimeout():

<html>
<head>
<title>changing Image</title>
<script type="text/javascript">
 var images= new Array();
 images[0]="image2.jpg";
 images[1]="image3.jpg";
 images[2]="image4.jpg";
 images[3]="image5.jpg";
 images[4]="image1.jpg";
 var x=0;

 var myinterval;
function timer()
{
    myinterval=setInterval(function(){slider()},3000);

    setTimeout(function(){stopslideshow()},30001);    //setTimeout invoked
}
function slider()
{
 document.getElementById("slide").src=images[x];
 if(x<4)
 {
     x=x+1;
   
 }
 else
 {
     x=0;
 }
}

function stopslideshow()

{

     clearInterval(myinterval);

}
</script>
</head>
<body onload="timer()">

<image id="slide" src="image1.jpg" style="border-style:solid; border-width:5px; border-color:green;" width="500" height="400"/>

</body>
</html> 

we can use
clearTimeout(timeoutvar)  to suspend the setTimeout() event.

where timeoutvar=setTimeout("function name",10000);
suppose you have provided 10 seconds of time interval in the setTimeout(function(),10000) and then you invoke clearTimeout(var) before 10 seconds from invoking setTimeout(),the function() will not be executed.

No comments:

Post a Comment