Simple Polling Solution Using setTimeout()

01-15-2020


We often find a need to repeatedly perform an action while some condition is met. A common example is the need to poll or call a URL repeatedly at a fairly regular interval while some condition exists. This might mean making an AJAX request to a third party service every 5 seconds until it responds with data or an error. In this blog post I’ll show you how to implement a simple polling solution using setTimeout() instead of setInterval().

Why not setInterval()?

If we want to perform an action say every 5 seconds, setInterval() seems like the best candidate. We can provide a callback function, an interval (in milliseconds) and we’re off to the races. But what happens when our AJAX call to a third party service takes longer than our interval value? If you’re familiar with the way that JavaScript’s call stack works and how it’s used to manage asynchronous actions this might, maybe, possibly seem obvious. Just in case here’s a diagram of what could (and probably will) happen.

Using setTimeout()

Using setTimeout to achieve our simple polling setup eliminates the potential for our call stack to fill up unnecessarily when there’s an issue with the action we’re trying to perform.

Example Code:

1
2
3
4
5
6
7
8
9
10
11
const makeApiCall = () => {

// Do Something, call an API maybe
// If you didn't get the response you were waiting for
// call again
setTimeout(makeApiCall(), 3000);

}

// Initiate call
setTimeout(makeApiCall(), 3000);