Window clearTimeout()
Method
Example
Prevent the setTimeout()
method from executing a function:
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
Definition and Usage
The clearTimeout()
method cancels a timeout previously established by calling setTimeout()
.
The clearTimeout()
method's parameter must be the ID value returned by setTimeout()
.
Note: To use the clearTimeout()
method, a global variable must be used when creating the timeout:
myVar = setTimeout("javascript function", milliseconds);
If the function has not yet been executed, we can use clearTimeout()
to prevent it.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
clearTimeout() | 1.0 | 4.0 | 1.0 | 1.0 | 4.0 |
Syntax
clearTimeout(id_of_settimeout)
Parameter | Description |
---|---|
id_of_setinterval | The value returned by the setTimeout() function, used as an identifier to cancel the scheduled action. |
Technical Details
| Return Value: | No return value. | | --- | --- |
More Examples
Example
The following example starts a counting program when the "Start Counting!" button is clicked. Clicking the "Stop Counting!" button stops the count, and clicking "Start Counting!" again will restart the count.
<button onclick="startCount()">Start Counting!</button>
<input type="text" id="txt">
<button onclick="stopCount()">Stop Counting!</button>
<script>
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById("txt").value = c;
c = c + 1;
t = setTimeout(function(){timedCount()}, 1000);
}
function startCount() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
</script>
Related Pages
Window Object: setInterval() Method
Window Object: setTimeout() Method
Window Object: clearInterval() Method