In this section, we will learn what the clearInterval() function is and how to use it in JavaScript.
Note: we’re assuming you’re already familiar with the `setInterval()` function.
What is clearInterval() in JavaScript? (Stop setInterval in JavaScript)
When we want to stop a timer that is set via the call to the `setInterval()` function, we use the `clearInterval()`.
If we call the `setInterval()` function, it will return an ID, which is basically a value of type Number. This ID is the identity of the timer that we’ve created via this function.
So the `clearInterval()` takes this ID (the return value of the call to the `setInterval()` function) as its argument and will stop the execution of that timer.
clearInterval() Function Syntax:
clearInterval(id);
The function takes one argument, and that is the id of the target setInterval() function that we want to remove its execution from our program.
Example: using clearInterval() Function in JavaScript
function sayHi(name){ console.log(`Hello ${name}`); } const id = setInterval(sayHi, 2000, "John Doe"); setTimeout(()=>{ clearInterval(id); },6000)
Output:
Hello John Doe Hello John Doe Hello John Doe
In this program, the message `Hello John Doe` only appears 3 times on the console. This is because we’ve set a `setTimeout()` function that will request the execution of its reference function after 6 seconds. Inside the body of the referenced function there’s a call to the `clearInterval()` function that takes the `id` value of the current timer as its argument.
So because after 6 seconds the `clearInterval()` ran, the current timer won’t be executed anymore.