Prerequisite: setTimeout() and setInterval()
clearTimeout()
The clearTimeout() function in javascript clears the timeout which has been set by setTimeout()function before that.
- setTimeout() function takes two parameters. First a function to be executed and second after how much time (in ms).
- setTimeout() executes the passed function after given time. The number id value returned by setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer.
Example:
<!DOCTYPE html> <html> <head> <title> HTML | DOM Windows clearTimeout() method </title> </head> <body> <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, 3000); } function stop() { clearTimeout(t); } </script> </body> </html> |


Explanation:
The GeeksForGeeks button color changes after 3 seconds for just one time. Click on Stop before 3 seconds after clicking GeeksForGeeks button to clear Timeout.
clearInterval()
The clearInterval() function in javascript clears the interval which has been set by setInterval() function before that.
- setInterval() function takes two parameters. First a function to be executed and second after how much time (in ms).
- setInterval() executes the passed function for the given time interval. The number id value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval.
Example:
<!DOCTYPE html> <html> <head> <title> HTML | DOM Windows clearInterval() method </title> </head> <body> <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, 3000); } function stop() { clearInterval(t); } </script> </body> </html> |


Explanation:
In this example, the GeeksForGeeks color changes and stays the same for every 3 seconds, 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
- Internet Explorer 4.0
- Firefox 1.0
- Opera 4.0
- Safari 1.0


