clear timeout js
Clear Timeout JS
Timeouts are a mechanism in JavaScript that allow you to delay the execution of a piece of code. If you have set a timeout and want to clear it before it executes, you can use the window.clearTimeout()
method.
Syntax:
clearTimeout(timeoutID);
The timeoutID
parameter is the ID of the timeout you want to clear. This ID is returned by the window.setTimeout()
method.
Example:
// Set a timeout
var timeoutID = setTimeout(function() {
alert('Hello world!');
}, 1000);
// Clear the timeout
clearTimeout(timeoutID);
In this example, we set a timeout to display an alert after 1 second. However, before the timeout can execute, we clear it using the window.clearTimeout()
method.
Multiple Ways:
- You can also use the
clearInterval()
method to clear a timeout. However, this method is intended for clearing intervals created with thewindow.setInterval()
method. - You can pass a function reference to the
window.clearTimeout()
method instead of the timeout ID. This function will then be used as a callback when the timeout is cleared.