The clearTimeout() method clears the time out that has been previously set by the setTimeout() function. The clearInterval() method clears the interval which has been previously set by the setInterval() function.
Following is the code for clearTimeout() and clearInterval() method −
Example
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .timeout { margin-right: 170px; display: inline-block; width: 200px; height: 200px; } .interval { display: inline-block; width: 200px; height: 200px; } .stopTimeout { margin-right: 100px; } </style> </head> <body> <h1>clearTimeout() & clearInterval() Method</h1> <div class="timeout" style="background-color: blue;"></div> <div class="interval" style="background-color: blue;"></div> <br /> <button class="startTimeout" onclick="startTimeout()">START TIMEOUT</button> <button class="stopTimeout" onclick="stopTimeout()">STOP TIMEOUT</button> <button class="startInterval" onclick="startInterval()"> START INTERVAL </button> <button class="stopInterval" onclick="stopInterval()">STOP INTERVAL</button> <div class="resultInterval"></div> <div class="resultTimeout"></div> <script> let resInterval = document.querySelector(".resultInterval"); let resTimeout = document.querySelector(".resultTimeout"); function changeColor(ele) { if (ele.style.backgroundColor == "blue") { ele.style.backgroundColor = "red"; } else { ele.style.backgroundColor = "blue"; } } let timeout; function startTimeout() { timeout = setTimeout( changeColor.bind(this, document.querySelector(".timeout")), 1500 ); resTimeout.innerHTML = "Timeout has been started"; } function stopTimeout() { clearTimeout(timeout); resTimeout.innerHTML = "Timeout has been cleared"; } let interval; function startInterval() { interval = setInterval( changeColor.bind(this, document.querySelector(".interval")), 1500 ); resInterval.innerHTML = "Interval has been started"; } function stopInterval() { clearInterval(interval); resInterval.innerHTML = "Interval has been cleared"; } </script> </body> </html>
Output
On clicking the “START TIMEOUT” and “START INTERVAL” button and waiting some seconds −
On clicking the “STOP TIMEOUT” and “STOP INTERVAL” button −