'How to stop nested setTimeout call after a fixed time?

I have this piece of code:

let timerId = setTimeout(function tick() {
   alert("tick");
   setTimeout(tick(), 1000);
 }, 1000);

This creates an infinite loop that doesn't end. How can I stop this setTimeout after suppose 10000 ms or 10 s?



Solution 1:[1]

A soluation is to push the timeout to array when everytime you create it and loop over the array to clear it.

    let arr = []
    let timerId = setTimeout(function tick() {
       console.log("tick");
       arr.push(setTimeout(tick(), 1000));
     }, 1000);


    setTimeout(function(){
    arr.forEach(i=>{
     window.clearTimeout(i)
     }))
     },10000)

But, it always stable to use setInterval():

let arr = []
setInterval(function tick() {
   console.log("tick");
 }, 1000);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James