Monday, May 10, 2010

JavaScript Timing Events

Wohoo! JavaScript has the equivalent of onEnterFrame and setTimeout! Here is a timer that you can start or stop (I got this from here):
<html>
<head>
<script type="text/javascript">
var c=0;//counter
var t;//timer object
var i=1000;//interval (1000 is one second)
var timer_is_on=0;//boolean on/off switch

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",i);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
</body>
</html>

No comments:

Post a Comment