/  Technology   /  Cancel or Stop the timer

Cancel or Stop the timer


To cancel or stop the timer and halt the execution of code, JavaScript offers the functions clearTimeout() and clearInterval(). Both setTimeout() and setInterval() return unique IDs. The clearTimeout() and clearInterval() functions use these IDs to clear the timer and to stop the execution of the code before the timer expires. Both take only one parameter, namely the ID.

Example : 

In this example, we will use clearTimeout() to clear the timer set by setTimeout(). Take a look at the example below to see how clearInterval() works in conjunction with setInterval().

Disable the regular interval

function ShowOutput() {
var systemdate = new Date();
document.getElementById("timer").innerHTML = systemdate.toLocaleTimeString();
function stopClock() {
var intervalID = setInterval(ShowOutput, 4000);
<p>Current system time: <span id="timer"> </span> </p>
<button onclick = "stopClock();" > Stop Clock </button>


Executing the above code will display the current system time on the web with a regular interval of three seconds. There is also a button on this page that allows you to disable the timer.

Every three seconds, the timer will display the updated time. Clicking on this Stop Clock button will disable the timer and stop updating the time.

Leave a comment