JavaScript short polling

Polling is a technique that the client asking the server for data (updates) at regular intervals (maybe every x seconds) and it has two types long/short polling. Polling is not a suitable architecture when designing a chat application which many clients, messages so it will waste resources but it suits applications like getting temperature updates every 30 seconds or 1Min.
In this article, we will discuss how to implement short polling in NodeJS and JavaScript

Short polling / Ajax polling

In ajax polling a client makes XHR(XMLHttpRequest) / Ajax request to server repeatedly (using interval) to check for new data.

  • A client initiates requests at small regular intervals (0.5 seconds).
  • The server prepares the responses and sends them back to the client just like normal HTTP requests.
  • The client repeats the above steps to get updates from the server.

The problem with Polling is that the client has to keep asking the server for any new data. As a result, a lot of responses are empty because the response may be delayed over the intervals, which creating HTTP overhead. Making repeated requests to the server wastes the resources.

Example of short polling

We will create a simple NodeJS server using express with a single REST GET API that generates a random number every time calling it.
Create a new NodeJS project polling inside this directory run the following commands:

  • npm init -y To initiate a NodeJS Project without answering questions and automatically populate all options with the default.
  • npm i express cors express to create a web application and cors to fix the cors issues a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.
  • Create a new file server.js
"use strict";
const express = require("express");
const cors = require("cors");
const PORT = process.env.PORT||5000;
const app = express();
app.use(express.json());
app.use(express.urlencoded({extended:false}));
app.use(cors());
app.get("/updates",(req,res,next)=>{
    let timeStamp = new Date().getTime();
    let randomNum = Math.floor(Math.random(0,10)*1000);
    return res.json({timeStamp,randomNum});
});
app.listen(PORT,()=>{
    console.log(`server is running at http://localhost:${PORT}`);
})

Then run this application using the following command node server.js

Now server is ready to send updates for the client. We will create a simple html page called client.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Short/Long polling</title>
</head>
<body id="body">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script>
        const shortPolling = ()=>{
	        setInterval(async() => {
                let response = await fetch(`http://localhost:5000/updates`);
                let data = await response.json();
                if(data.randomNum%2===0){
                    document.getElementById("body").style.background="red";
                }else{
                    document.getElementById("body").style.background="white";
                }
	        }, 5000);
	   	}
	shortPolling();
    </script>
</body>
</html>

Open this page in the browser and based on the response from a server the background color will change from white to red and vice versa.

Subscribe to our Newsletter

Subscribe to tech-hour website to get all updates, new articles, new courses and projects. No spam ever. Unsubscribe at any time.