Using Timers in JavaScript - Turning Up the Volume
(Page 5 of 7 )
Using a setInterval() function is identical to using a setTimeout() function in a loop. To illustrate this, consider the following example by rewriting the countdown clock example from a few pages back.
<html>
<head>
<script language="JavaScript">
var i=10;
function countDown()
{
if(i > 0)
{
document.forms[0].elements[0].value=i;
i = i-1;
}
else
{
alert("Happy New Year!");
}
}
window.setInterval("countDown()", 1000);
</script>
</head>
<body>
<form>
<input type="text" name="counter" size="3">
</form>
</body>
</html>
In this case, I've used the setInterval() method instead of the setTimeout() method to call the countDown() function over and over again. Note the difference between the version above and the one a few pages back - above, the call to setInterval() is outside the loop, whereas earlier, the call to setTimeout() was inside the loop.
Here's one more example, this one making a <div> appear when the mouse moves over a link and automatically hiding it again after 3 seconds:
<html>
<head>
<script language="JavaScript">
function on()
{
if(document.all)
{
// make <div> visible
document.all['volume'].style.visibility='visible';
// after 3 seconds, make it invisible
window.setInterval("document.all['volume'].style.visibility='hidden'",3000);
}
if(document.layers)
{
// make <div> visible
document.volume.visibility='show';
// after 3 seconds, make it invisible
window.setInterval("document.volume.visibility='hide'",3000);
}
if(!document.all && document.getElementById)
{
// make <div> visible
document.getElementById("volume").style.visibility="visible";
// after 3 seconds, make it invisible
window.setInterval("document.getElementById('volume').style.visibility='hidd
en'",3000);
}
}
</script>
</head>
<body>
<a href="#" onMouseOver="javascript:on();">Show Volume Control</a>
<div id="volume" style="color:white; font-face:Arial; background:black;
position:absolute; left:550; top:200; height:150; visibility:hidden;">
Volume<br> control<br> slider<br> here
</div>
</body>
</html>
Next: Sliding Around >>
More JavaScript Articles
More By Nariman K, (c) Melonfire