Long polling is pretty cool, really. It lets web apps feel a bit more like they're in real-time. The way it works is quite simple: the client makes a request to the server and the server keeps the connection open until there's new data. Once the client gets the data, it makes a new request immediately, and this cycle goes on, making sure your app gets a steady stream of updates. Super useful for things like chat applications and live notifications!
First thing’s first, let's set up the server. We'll do this using Node.js and the Express framework.
Install Node.js and npm if you haven’t yet.
Create a new directory for your project and hop into it.
Run npm init -y
to set up a new Node.js project.
Install Express by running npm install express
.
Now, create a file named server.js
and add the following code:
const express = require('express');
const app = express();
const PORT = 3000;
let latestData = null;
app.use(express.json());
app.get('/poll', (req, res) => {
const checkForData = () => {
if (latestData) {
res.json({ data: latestData });
latestData = null;
} else {
setTimeout(checkForData, 1000);
}
};
checkForData();
});
app.post('/data', (req, res) => {
latestData = req.body.data;
res.status(201).send('Data received');
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Here's what’s happening:
/poll
endpoint continuously checks if there's new data every second. When there is data, it sends it back to the client./data
endpoint lets us simulate new data being sent to the server.Now, let's set up the client side. Create an HTML file named index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Long Polling Example</title>
</head>
<body>
<h1>Long Polling Example</h1>
<div id="dataDisplay">Waiting for data...</div>
<script>
async function longPoll() {
try {
const response = await fetch('/poll');
if (!response.ok) {
throw new Error(`Error: ${response.status}`);
}
const result = await response.json();
document.getElementById('dataDisplay').innerText = `Data: ${result.data}`;
} catch (error) {
console.error('Polling error:', error);
await new Promise(resolve => setTimeout(resolve, 5000));
} finally {
longPoll();
}
}
longPoll();
</script>
</body>
</html>
Here's the breakdown:
longPoll
function is defined asynchronously.fetch
call to the /poll
endpoint.Start your server by running node server.js
.
Open your index.html
in a web browser.
The page will keep polling the server and update the displayed data as new data comes in.
To see it in action, you can simulate new data by sending a POST request to the /data
endpoint. You can use tools like Postman or cURL:
curl -X POST \
-H "Content-Type: application/json" \
-d '{"data": "This is new data"}' \
http://localhost:3000/data
When you do this, the new data should appear on your web page promptly.
So, that's how you can set up long polling with JavaScript async functions! The client makes repeated requests to the server, which only responds when there's new data. This setup helps your web app stay updated in real-time without making unnecessary network requests continuously. Plus, it’s kinda fun to set up something that feels so immediate and responsive!