Can you please explain in details “contexts will build up: memory leak” statement?
Using recursive setTimeout guarantees that method which we want to execute on some interval will never show up 2 or more times on the execution queue. Since next call in the recursion will only be initiated if the method is fully executed.
You sure need to use some kind of flag here, in order to stop the recursion at some point. In this light, it’s very unlikely that contexts will ever build up while using this approach.
Further on, you are right, you can introduce flag to setInterval as well and stop the execution immediately if desired condition is met. That is legit, but I would still prefer recursive setTimeout. It does not require any decision making on when it needs to be executed, just when it needs to stop calling it self again. Which is IMHO way less prone to errors.
Thanks for the comment!