How to clear setInterval() in JavaScript?

In order to clear setInterval() assign it to the variable and use the clearInterval() method.

var intervalName = setInterval(() => {
        clearInterval(intervalName);
}, 1000);

Example:

Print numbers from one to five inside the console in 10 milliseconds intervals.

<script>
    var i = 1;
    
    var myInterval = setInterval(() => {
        console.log(i);
        i++;

        if(i > 5) {
            clearInterval(myInterval);
        }
    }, 10);
</script>

Output (console):

1

2

3

4

5