How to clear setInterval() after specific time in JavaScript?

We can do this with simple counter and stopping the interval after a specific amount of iterations, or with setTimeout() function.

In most cases, I recommend the second method, because it should also work if the user will be on the another browser tab.

Example 1:

<script>
    var i = 0;

    var myInterval = setInterval(() => {
        i++;

        console.log('hello');

        if(i >= 5) {
            clearInterval(myInterval);
        }
    }, 100);

</script>

Example 2:

<script>
    var myInterval = setInterval(() => {
        console.log('hello');
    }, 100);

    var myTimeout = setTimeout(() => {
        clearInterval(myInterval);
    }, 500);
</script>