Table of contents
1.
Introduction
2.
What is clearTimeout() in Javascript??
3.
Syntax of clearTimeout() in Javascript
4.
Parameters of JavaScript clearTimeout()
5.
Return Value of JavaScript clearTimeout()
6.
Exceptions of JavaScript clearTimeout()
7.
How does clearTimeout() in JS work?
8.
Practical Usage of JSclearTimeout()
9.
Supported Browser
10.
Frequently Asked Questions
10.1.
What does clearTimeout() need as an argument?
10.2.
Can clearTimeout() be called multiple times on the same timer?
10.3.
Does clearTimeout() work on intervals set by setInterval()?
10.4.
Can clearTimeout() be used without storing the timeout ID?
11.
Conclusion
Last Updated: Nov 12, 2024
Easy

JavaScript clearTimeout()

Author Nikunj Goel
0 upvote

Introduction

JavaScript, as a powerful, high-level, and interpreted programming language, has a vast library of built-in functions. These functions make it a versatile tool for web development. One such function is the clearTimeout() function, often used in conjunction with setTimeout(). This article will discuss what clearTimeout() is, how it works, and when to use it.

JavaScript clearTimeout()

What is clearTimeout() in Javascript??

In Javascript, clearTimeout() is a method that stops a previously set timer created by setTimeout(). setTimeout() is a function that executes a piece of code after a specified delay.

Syntax of clearTimeout() in Javascript

The syntax for setTimeout() is:

let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...);
You can also try this code with Online Javascript Compiler
Run Code

 

The setTimeout() function returns an ID that can be used to stop the timer. To cancel the timer, you can pass this ID to clearTimeout().

The syntax for clearTimeout() is:

clearTimeout(timerId);
You can also try this code with Online Javascript Compiler
Run Code

Parameters of JavaScript clearTimeout()

The clearTimeout() function in JavaScript takes a single parameter: the ID of the timeout to be cleared. This ID is generated when you set a timeout using setTimeout(). Passing this ID into clearTimeout() stops the timer, preventing the specified function from executing if the delay has not yet expired.

Return Value of JavaScript clearTimeout()

The clearTimeout() function does not return any value; it simply cancels the timeout associated with the provided ID.

Exceptions of JavaScript clearTimeout()

The clearTimeout() function does not throw any exceptions if an invalid or non-existent ID is passed. If the ID doesn’t match any active timer, the function simply does nothing. This silent handling allows clearTimeout() to be called without risk of breaking code execution, even if the timer has already expired or was never set.

How does clearTimeout() in JS work?

Let's create a simple example. Suppose we set a function to execute after 5 seconds using setTimeout():

let timerId = setTimeout(() => {
    console.log("This message will never show up.");
}, 5000);
You can also try this code with Online Javascript Compiler
Run Code

 

Now, if we use clearTimeout(timerId); before the 5 seconds pass, the message will never be logged to the console because the timer will be cancelled.

clearTimeout(timerId);
You can also try this code with Online Javascript Compiler
Run Code

 

As soon as JavaScript executes clearTimeout(), it stops the timer and the code within setTimeout() will not be executed.

Practical Usage of JSclearTimeout()

In real-world scenarios, clearTimeout() can be very useful. For example, consider a scenario where you're creating a live search feature. As a user types into a search box, a request is sent to the server to fetch matching results.

However, you don't want to send a request for every keystroke — that would be inefficient. You decide to use setTimeout() to delay the request by 1 second, providing time for the user to finish typing. But what happens if the user types another character within that 1 second? The request should be cancelled and a new one created.

Here is where clearTimeout() comes into play. You can cancel the previous request timer and create a new one with every keystroke:

let timerId;
document.getElementById('search-box').addEventListener('keyup', function(e) {
    clearTimeout(timerId);
    timerId = setTimeout(() => {
        // send request
    }, 1000);
});
You can also try this code with Online Javascript Compiler
Run Code

Supported Browser

FeatureGoogle ChromeMozilla FirefoxSafariMicrosoft EdgeOperaInternet Explorer
clearTimeout() SupportYesYesYesYesYesYes (limited in older versions)
JavaScript CompatibilityYesYesYesYesYesLimited (varies by version)
ECMAScript 5+ SupportYesYesYesYesYesLimited (IE11 and below)
Window ObjectYesYesYesYesYesLimited in older versions

Frequently Asked Questions

What does clearTimeout() need as an argument?

clearTimeout() takes one argument, which is the ID value of the timer returned by the setTimeout() function.

Can clearTimeout() be called multiple times on the same timer?

Yes, it can be called multiple times, but after the first call, subsequent calls will have no effect.

Does clearTimeout() work on intervals set by setInterval()?

No, clearTimeout() does not work on intervals set by setInterval(). It is specifically designed to stop timeouts created by setTimeout(). To clear intervals, the clearInterval() method should be used instead.

Can clearTimeout() be used without storing the timeout ID?

clearTimeout() cannot be used effectively without storing the timeout ID, as the ID is needed to identify and cancel the specific timeout. Without it, the timeout will continue until completion.

Conclusion

clearTimeout() is an essential function in JavaScript, especially when dealing with timers or delays in code execution. Its primary use is to stop the execution of the function specified in setTimeout(). Mastering clearTimeout() can help optimize your web applications, making them more efficient and responsive. It's these little functions and their correct use that can truly enhance the performance of your web application.

Live masterclass