To stop and clear the instance of running Javascript setTimeout timer clearTimeout is used. clearTimeout stops the timer started by setTimeout function of Javascript.
JavaScript clearTimeout syntax:
clearTimeout (TimerID);
JavaScript cleatTimeout function takes 1 parameter:
TimerID: timer id of the timer instance initiated by setTimeout function.
setTimeout method returns the timerID when it is executed in javascript code.
Example of JavaScript clearTimeout with setTimeout function:
HTML code:
<div id="myTime"></div>
<input type="button" value="start Timer" onclick="startTimer();"/>
<input type="button" value="stop Timer" onclick="stopTimer();"/>
JavaScript code:
<script language="javascript">
var timeOut;
function startTimer()
{
document.getElementById('myTime').innerHTML = Date();
timeOut = setTimeout("startTimer();",1000);
}
function stopTimer()
clearTimeout(timeOut);
</script>
In the above example HTML Div element is used to display the output. In Javascript code 1 variable is declared to store the setTimeout timerID. startTimer function has setTimeout function that calls startTimer function after every 1000 milliseconds and the timeout variable stores the timerID returned by the setTimeout method.
JavaScript code in the above example has timeout variable declared globally at the top so that it could be accessed by all the functions any time. In stopTimer function clearTimeout method is used to cancel the setTimeout by passing the stored timerID in timeout variable.
Currently rated 2.5 by 4 people
Tags: javascript, javascript settimeout, javascript cleartimeout, javascript delay, javascript time, javascript use, javascript tutorials, learn javascript, javascript examples
10/11/2008 3:28:12 AM