I got another reminder today of how bad setInterval can be. You just don’t hear developers talking about the problems with setInterval. In fact, I’ve seen numerous tutorials where good developers are using it in their examples. We need to start addressing this and start talking about the problems with setInterval.
This code snippet is pretty simple. It does an GET request to an API point, looking to retrieve all posts and dump the data to the console. What would happen if there was an error on the API server? Would our loop stop doing the request? No, it would keep executing over and over, even if our AJAX call was being held up. This could hold up our whole server and create big performance problems for us.
There is a better way! Let’s use setInterval’s little cousin setTimeout. We can use setTimeout to get the functionality we want, with our little friend recursion.