Executing code in intervals with…

Executing code in intervals with JS: setTimeout() and setInterval()

There are two ways you can execute the code in intervals with JS, but which one to use?

rtIXD7RoYl

OD9HaMdfuk

How do recursive setTimeout() and setInterval() differ?

The difference between the two versions of the above code is a subtle one.

  • Recursive setTimeout() guarantees the same delay between the executions. (For example, 100ms in the above case.) The code will run, then wait 100 milliseconds before it runs again—so the interval will be the same, regardless of how long the code takes to run.
  • The example using setInterval() does things somewhat differently. The interval you chose includes the time taken to execute the code you want to run in. Let’s say that the code takes 40 milliseconds to run — the interval then ends up being only 60 milliseconds.
  • When using setTimeout() recursively, each iteration can calculate a different delay before running the next iteration. In other words, the value of the second parameter can specify a different time in milliseconds to wait before running the code again.
    When your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive setTimeout() — this will keep the time interval constant between executions regardless of how long the code takes to execute, and you won’t get errors.

Resource: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals

#javascript #setinterval #settimeout


Comments

Leave a comment