Stop, Clear Timeout
How to stop or cancel a timeout operation in javascript!
Explanation
Object:
WindowMethod or Function:
clearTimeout()Syntax: clearTimeout(instance-name);
To stop or clear a timeout execution we can use the method clearTimeout. For using the method we should use the identifier or instance of the setTimeout.
The steps are as follows
a) Capture the instance or identifier of the time out call in a variable while calling setTimeout
Example:
var ctime = setTimeout("xxxxx",30000);
b) use the identifier as argument to stop or clear or cancel the timeout call.
Example:
clearTimeout(ctime);
Example:
This example will repeatedly add 1 to a number and show an alert after every 3 seconds (3000 milliseconds). clearTimeout will be called once you click stop button and will cancel the repeated execution.
Code:
<script language=javascript>
var x = 0; var timer; function testtimeout(){
x = x+1;
alert(" value of x is - "+x);
timer = setTimeout("testtimeout()",3000);
}
function stoper() {
clearTimeout(timer);
}
</script>
<form name=xcv>
<input type=button onClick="testtimeout()" value=start>
<input type=button onClick="stoper()" value=stop>
</form>
Result: