The clearTimeout() method in JavaScript clears the timer which has been set by a setTimeout() method.

var timer = setTimeout(function(){
  //Code that will after 1000 milliseconds
}, 1000);
    
function clearTimer(){
  clearTimeout(timer);
}

In the code above, the setTimeout() method will run the function after 1000 milliseconds(1 second). We can change that parameter to be however long we want to execute the function call.

You can see that we have another function called clearTimer(). We can stop the setTimeout() method from running the function by using the clearTimeout() method call. We can do this by setting a variable to the setTimeout() method, var timer = setTimeout(), as seen above, and then clearing it by using the clearTimeout() method in JavaScript, clearTimeout(timer);.

We find the best way to learn how to use the clearTimeout() method is to see an example of it. So let’s take a look at one below.


To see how the clearTimeout() method in JavaScript works, let’s create a simple example. Here is code that will run a simple timer.

Let’s start with the simple HTML setup:

Start Timer
Stop Stop

Below will be the JavaScript code to make this very simple timer work.

var timer;
function startTimer(){
  timer = setTimeout(function(){
    alert('5 seconds are up');
  }, 5000);
};

The basic overview of this code is that the setTimeout() method will run a function after 5 seconds have passed. And when that happens, an alert box will be fired stating that “5 seconds are up”.

We also have a button to stop the timer. When this button is pressed, our timer will be stopped and cleared. We will do this using the clearTimeout() method.

Here are the functions for our simple timer.

var timer;
function startTimer(){
  timer = setTimeout(function(){
    alert('5 seconds are up');
  }, 5000);
};

function stopTimer(){
  clearTimeout(timer);
  alert('Timer has been stopped');
};

Here is the code for you to try this simple timer out for yourself.

Code Output:

Start Timer
Stop Stop

Full Code:

Start Timer
Stop Stop

Hopefully this article has been useful for you to understand how the clearTimeout() method in JavaScript works.

Categorized in:

JavaScript,

Last Update: March 11, 2024