JavaScript > Timer

clearTimeout in JavaScript

How to clear a timer set with the setTimeout in JavaScript?


clearTimeout

clearTimeout is an method in JavaScript {clearTimeOut() method}, Which is used to clear a timer set with the setTimeout() method. The clearTimeOut() method having only one required parameter, i.e 'setTimeout ID', nothing but the ID value of the timer which is returned by the setTimeout()  method.

In JavaScript, by using clearTimeOut() method we can clear a timer set with the setTimeout() method.

Stopping the alert before it display on the window.

<p>Click the "Alert" button to get the alert. <br />Click the "Stop Alert" button to stop the alert. (We must click before the alert display time on window, the alert display time is 4 seconds)</p>
<input type="button" value="Alert" onclick="myAlert()"/>
<input type="button" value="Stop Alert" onclick="myStopAlert()"/>

<script>
    var a;

    function myAlert() {
        a = setTimeout(function () { alert("TechFunda") }, 4000);
    }
     
    function myStopAlert() {
        clearTimeout(a);
    }
</script>

In the above code snippet we have created an alert with the setTimeout() method, after clicking the "Alert" button we can find the alert after 4 seconds on the window.

To stop the alert before displaying on the window we need to click the "Stop Alert" button, which is connected to the myStopAlert() function of clearTimeOut() method. "Stop Alert" button must be click before the alert displaying time on window. To check the output of above code snippet, click here.

Stopping the run timer.

<label id="lblText">0</label>
<input type="button" id="btnTest" onclick="TestFunction()" value="Start Timer" />
<input type="button" id="btnStop" value="Stop Timer" onclick="StopCount()" />

<script>
    var count = 0;
    function TestFunction() {
        count++;
        document.getElementById("lblText").innerHTML = count;
        t = setTimeout("TestFunction()", 1000);
    }
    function StopCount() {
        clearTimeout(t);
    }
</script>

Stop run timer  

In the above code snippet, we have implemented a timer using setTimeout() method that stores the tick into the tvariable. This timer executes inside the “TestFunction” function that fires when the “Start Timer” button is clicked.

In the click event of “Stop Timer” button we have called the “StopCount()” function that calls clearTimeOut() method by passing the t variable that stops the timer.

NOTE: The timer starts after clicking on "Start timer" button, and it will run until we click on "Stop Timer" button. Again if we click on "Start Timer" button, the timer satrts running from where it stopped.

OUTPUT


 Views: 9732 | Post Order: 193



Write for us






Hosting Recommendations