In this blog post you’ll learn the javascript method that stops the setTimeout method from being executed. The method name is clearTimeout().
clearTimeout() Method.
Description:
To stop the setTimeout method from being executed you can use the javascript clearTimeout().
Store the setTimeout method inside the variable name. Then add that variable name inside the clearTimeout() method (like this clearTimeout(variable name)).
Syntax:
JavaScript
clearTimeout(variable);
Here, variable is the variable name in which setTimeout method is stored.
variable name is required in this method.
Example 1:
JavaScript
let mytimeout = setTimeout(() => {
// Text display after two seconds.
document.write("Welcome to maketechstuff.com");
}, 2000);
// To stop the execution of the setTimeout() method which is store in side the variable "mytimeout".
// Remove this line to execute the setTimeout.
clearTimeout(mytimeout);
Stop the text from being display within 5 second.
JavaScript
<!DOCTYPE html> <html lang="en"> <!-- maketechstuff.com --> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>clearTimeout Method | Maketechstuff.com</title> <style> * { padding: 0px; margin: 0px; } body { width: 100%; height: 100vh; } .container { padding: 40px; font-size: 20px; } p { margin: 10px 0px; } .text { display: none; } </style> </head> <body> <div class="container"> <p class="instruction"></p> <p class="text">Welcome to maketechstuff.com</p> <button class="button">Click here to stop</button> </div> </body> <script> let button = document.querySelector(".button"); let instruction = document.querySelector(".instruction"); let text = document.querySelector(".text"); // Just to display the seconds. let i = 10; let myinterval = setInterval(() => { if (i == 1) { clearInterval(myinterval); } instruction.innerHTML = "Stop the text from being display in <b>"+ i-- + "</b> seconds OR Do nothing to see the text."; }, 1000); let mytimeout = setTimeout(() => { // Text display after 10 seconds. text.style.display = "block"; // Disabling the button. button.disabled = true; }, 10000); // By click on button, execution of the setTimeout() method which is store in side the variable "mytimeout" will stop. button.onclick = function () { clearTimeout(mytimeout); instruction.innerHTML = "You stopped the text from being display within 10 seconds"; // stop the seconds. By stoping the interval method which is stored in myinteval variable. clearInterval(myinterval); } </script> </html>
Blog posts in which I've used the clearTimeout method:
Detects the button hold in JavaScript.
So that's it for the clearTimeout() method. Its use to stop the executionsetTimeout method. If you have any question or suggestion you can write in the comment section.
Share your thoughts.