Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

Follow publication

Polling in JavaScript

A guide to building your own polling function to query for updates

Trey Huffine
Level Up Coding
Published in
4 min readJan 15, 2020

--

Polling is a technique where we check for fresh data over a given interval by periodically making API requests to a server. For example, we can use polling if there is data that changes frequently or we need to wait for the server to transition a given state. Polling is a simple alternative to web sockets or server events.

This article will first describe when we would need polling, provide a poll function implementation in JavaScript, and then show how it would be used in a mock API.

I want to teach you how to ace your coding interviews ➡️.

When We Would Use Polling

A real-world use case for polling would be if we used a third-party authentication provider (such as Firebase or Auth0 ) and need to wait on the result before we proceed. When a user registers, we send the user’s data to the authentication provider from the client. Then on the server, we wait for the response from the authentication provider and then create a user in our database.

During this whole process, the client must wait through the authentication and the user creation on our server. Since we know this process will either succeed or fail reasonably quickly, we can be comfortable implementing a poll that will make API requests to our server every 1 second until we complete the process of registering and creating a new user.

Another example when a poll could be useful is if we’re tracking a user’s location on a map. In an app like Uber, we are able to watch our driver approach to pick us up by repeatedly polling for the most recent coordinates. Since this data changes frequently, we’ll set up an interval to poll for the location, ensuring we have up-to-date data.

Polling Implementation

We will write a simple poll function that uses promises to resolve the results from the fetch. I’ll paste the code below and…

--

--

Written by Trey Huffine

Founder | Software Engineer. Building products that empower individuals.

Responses (2)

Write a response