Prerequisite: setTimeout() and setInterval()
JavaScript clearTimeout() Function: The clearTimeout() function in javascript clears the timeout which has been set by the setTimeout()function before that.
Syntax:
clearTimeout(name_of_setTimeout)
Parameters: The clearTimeOut() function takes a single parameter.
- name_of_setTimeout: It is the name of the setTimeOut() function whose timeout is to be cleared.
Example: In this example, we will write a function to clear the timeout set by the setTimeout() function using the clearTimeout() function.
HTML
< button id = "btn" onclick = "fun()" style = "color: blue;" >
GeeksForGeeks</ button >
< button id = "btn" onclick = "stop()" >Stop</ button >
< script >
var t;
function color() {
if (document.getElementById('btn').style.color == 'blue') {
document.getElementById('btn').style.color = 'green';
} else {
document.getElementById('btn').style.color = 'blue';
}
}
function fun() {
t = setTimeout(color, 2000);
}
function stop() {
clearTimeout(t);
}
</ script >
|
Output: The GeeksForGeeks button color changes after 2 seconds just one time. Click on Stop 2 seconds after clicking the GeeksForGeeks button to clear Timeout.
JavaScript clearInterval() Function: The clearInterval() function in javascript clears the interval which has been set by the setInterval() function before that.
Syntax:
clearInterval(nameOfInterval)
Parameters: The clearInterval() function takes a single parameter.
- nameOfInterval: It is the name of the setInterval() function whose interval is to be cleared.
Example: In this example, we will write a function to clear the interval set by the setInterval() function using the clearInterval() function.
HTML
< button id = "btn" onclick = "fun()" style = "color: blue;" >
GeeksForGeeks</ button >
< button id = "btn" onclick = "stop()" >Stop</ button >
< script >
var t;
function color() {
if (document.getElementById('btn').style.color == 'blue') {
document.getElementById('btn').style.color = 'green';
} else {
document.getElementById('btn').style.color = 'blue';
}
}
function fun() {
t = setInterval(color, 1000);
}
function stop() {
clearInterval(t);
}
</ script >
|
Output: In this example, the GeeksForGeeks color changes and stays the same every second, after that it changes again. Click on Stop to clear the interval.
Supported Browser: The browser supported by clearTimeout() & clearInterval() Method are listed below:
- Google Chrome 1.0
- Edge 12.0
- Internet Explorer 4.0
- Firefox 1.0
- Opera 4.0
- Safari 1.0
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.