recursive function vs setInterval vs setTimeout javascript

Be carefull.. your first code would block JavaScript event loop.

Basically in JS is something like list of functions which should be processed. When you call setTimeout, setInterval or process.nextTick you will add given function to this list and when the right times comes, it will be processed..

Your code in the first case would never stop so it would never let another functions in the event list to be processed.

Second and third case is good.. with one little difference.

If your function takes to process for example 10ms and interval will be yours 60ms..

  • function with setInterval will be processed in times: 0-10, 60-70, 120-130, … (so it has only 50ms delay between calls)
  • But with setTimeout it will be:
    • if you call func first: 0-10, 70-80, 140-150, 210-220, …
    • if you call setTimeout first: 60-70, 130-140, 200-210, …

So the difference is delay between starts of your function which can be important in some interval based systems, like games, auctions, stock market.. etc..

Good luck with your recursion 🙂

Leave a Comment