Fire Timer event in JavaScript

Description

The following code shows how to fire Timer event.

Example


<HTML>
<HEAD>
<SCRIPT>
var timerID;<!--from   w ww.  j av a  2 s.  c  o m-->
var x;

function Thing (name) {
this.name = name;
}

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

function startIt (name) {
x = new Thing (name);
timerID = setInterval("fireIt()", 1000);
}

function stopIt() {
clearInterval(timerID);
}

</SCRIPT>
</HEAD>
<BODY>
<FORM name="theForm">
Name your object:<input type=text name="txtName">
<input type=button value="Start!" onClick="startIt (txtName.value);">
<input type=button value="Stop!"  onClick="stopIt();">
<textarea name="txtFired" cols = 60 rows=20></textarea>
</FORM>
</BODY>
</HTML>

Click to view the demo

The code above generates the following result.

Fire Timer event 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 ...