Monday, May 20, 2024

SetInterval vs Timeout

 https://www.reddit.com/r/learnjavascript/comments/f4mr07/what_happens_if_your_function_takes_longer_than/

You should avoid using setInterval() in this way.

The problem with setInterval() is that it keeps firing the event every 3 seconds (or whatever), even if the previous event hasn't finished yet.

If your response time is slower than the interval time, this can cause major problems with requests piling up on top of each other and maybe not even responding in the same order that they were requested.

This will become more and more noticeable the smaller the interval you set, but it can be a problem even for big intervals if you have any kind of blocking event in your JS code - an alert() box would be the classic example - as you can end up with large numbers of interval events piling up waiting for the alert to be cleared, and then all firing at once.

A better solution is to use a self-firing setTimeout().

This would use setTimeout() to start the event sequence, which then calls another identical setTimeout() call internally when its event is completed. This ensures you will never have multiple events piling up like you can with setInterval().


https://stackoverflow.com/questions/13337042/how-does-a-constant-setinterval-affect-page-functionality-does-it-slow-down-res

https://stackoverflow.com/a/18493485/5759460

https://stackoverflow.com/questions/1802936/stop-all-active-ajax-requests-in-jquery/42312101#42312101

No comments:

Post a Comment