Start a timer and cancel a timer in JavaScript

Description

The following code shows how to start a timer and cancel a timer.

Example


<!--  ww  w. j  a  va2  s .c  o m-->
<HTML>
<HEAD>
<SCRIPT>
var myTimer;


function fireIt () {
var now = new Date();
var displayStr = now + "\r\n";
window.document.theForm.myOutput.value = displayStr;
}
function startIt () {

myTimer = setInterval("fireIt()", 1000);
}
function stopIt() {
clearInterval(myTimer);
}

</SCRIPT>
</HEAD>
<BODY>
<TABLE>
<FORM name="theForm">
<input type=button value="Start!" onClick="startIt ();">
<input type=button value="Stop!" onClick="stopIt();">
<textarea name="myOutput" cols = 60 rows=20></textarea>
</FORM>
</TABLE>
</BODY>
</HTML>

Click to view the demo

The code above generates the following result.

Start a timer and cancel a timer in JavaScript
Home »
  Javascript Tutorial »
    Event »
      Timer Event
Javascript Tutorial Timer Event
Clear the timer in JavaScript
Create a time out timer in JavaScript
Create text move animation with timer in Ja...
Fire Timer event in JavaScript
Set the timeout for the timer according to ...
Start a timer and cancel a timer in JavaScr...
Stop a time out timer in JavaScript
Use timer in JavaScript
Use window.clearInterval() to stop a timer ...
Use window.clearTimeout() to stop timer in ...