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:

  • 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




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
    <button id="btn" onclick="fun()" style="color: blue;">
        w3wiki</button>
    <button id="btn" onclick="stop()">Stop</button>
    <script>
        let 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>
</body>
 
</html>


Output: The w3wiki button color changes after 2 seconds just one time. Click on Stop 2 seconds after clicking the w3wiki button to clear Timeout. 

JavaScript clearTimeout() & clearInterval() Method

In JavaScript there are many inbuilt functions clearTimeout() and clearInterval() methods are some of them. when we use setTimeout() and setInterval() in any JavaScript program then it must clear the time used in those functions so we use the clearTimeout() and clearInterval() methods.

Similar Reads

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....

JavaScript clearInterval() Function

...