What are use of “clearTimeout” and “clearInterval” in JS?

Asked 19-Jul-2021
Viewed 478 times

1 Answer


0

The setTimeout() and setInterval() methods return a unique id of our code and unless we store that unique id in a variable, we can prevent this code by passing it as a parameter to the clearTimeout() or clearInterval() method. can. If in a specific situation we want to stop the above code from being executed, then we can do this work by using clearTimeout() and clearInterval() methods. 

clearTimeout()

Syntax
clearTimeout() // clear the current timeout variable
clearTimeout( time out variable ) // claer the given variable

Example 

var id1 = setTimeout(function(){console.log('Hello')}, 3000);

clearTimeout(id1);

clearInterval()

Syntax

clearInterval() // clear the current interval variable
clearInterval( time out variable ) // claer the given interval variable 
Example
var id2 = setInterval(function(){console.log('Hello')}, 1000);

clearInterval(id2);