JavaScript clearTimeout() Function Tutorial

In this section, we will learn what the clearTimeout() function is and how to use it in JavaScript.

Note: we’re assuming you’re already familiar with the `setTimeout()` function.

What is clearTimeout() in JavaScript? (JavaScript Cancel Timer)

Sometimes we want to cancel a timer that we’ve created with the call to the `setTimeout()` function before its execution.

This is where we can use the `clearTimeout()` function.

The `clearTimeout()` function takes the return value of the call to the `setTimeout()` function to specify what timer to cancel.

clearTimeout() Function Syntax:

clearTimeout(id);

This function takes one argument, and that is the id number of the target timer that we want to cancel its execution (the one that was created using the setTimeout function).

Example: using clearTimeout() function in JavaScript

function sayHi(name){
  console.log(`Hello ${name}`);
}
const id = setTimeout(sayHi, 1000, "John Doe"); 
clearTimeout(id);

Here, if we didn’t use the `clearTimeout()` function, after one second delay, the execution engine will send the message `Hello John Doe` to the browser’s console.

But we used the `clearTimeout()`and cancel this timer. For this reason, the message won’t appear on the console anymore.

More to Read:

JavaScript setInterval() function tutorial 

JavaScript clearInterval() function tutorial 

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies