Long Polling vs WebSocket in JavaScript: An Epic Battle for Real-Time
\n\nOnce upon a time, in an era when the internet was slow and browsers were simple, the only way to find out that new data had appeared on the server was to press F5. Then AJAX came along, and we learned to manually poll the server. But what if data should arrive on its own, without our involvement? Welcome to the world of real-time communications.
\n\nIn this article, we will break down the two main approaches that still divide the developer community: the good old Long Polling and the modern, bold WebSocket. We will write code in JavaScript, look under the hood, and understand which tool to choose for your next project. If you want to understand long polling vs websocket once and for all — you are in the right place.
\n\nThe Problem: How to Make the Server Speak First?
\n\nHTTP is a unidirectional protocol. The client (browser) sends a request, the server responds — and that's it, lunch is over. But in the real world (chats, stock quotes, notifications), data needs to flow in the opposite direction. For a long time, developers had to improvise. Here are the two main ways to solve this problem.
\n\nLong Polling: A Clever Trick with Time
\n\nImagine you call customer support and say: "I'll wait on the line until an operator is free." You don't hang up. That's exactly how Long Polling works.
\n\nHow it works:
\n- \n
- The client sends a regular HTTP request. \n
- The server does not respond immediately if there is no data. It "hangs" and waits. \n
- As soon as data appears — the server sends a response. \n
- The client processes the response and immediately opens a new connection. \n
Client-side code (JavaScript):
\nfunction longPoll() {\n fetch('/updates')\n .then(response => response.json())\n .then(data => {\n console.log('New data:', data);\n // Immediately start a new poll\n longPoll();\n })\n .catch(error => {\n console.error('Error, reconnecting in 2 sec:', error);\n setTimeout(longPoll, 2000);\n });\n}\n\n// Start\nlongPoll();\n\nPros:
\n- \n
- Works on any server and any browser (even IE6). \n
- Does not require special protocols — pure HTTP. \n
- Passes through any corporate proxies and firewalls. \n
Cons:
\n- \n
- Each message is a new HTTP request (headers, cookies, overhead). \n
- The server holds many open connections (the C10k problem — 10 thousand clients). \n
- Latency is higher than WebSocket. \n
WebSocket: A Permanent Communication Channel
\n\nWebSocket is like an open line between a spaceship and mission control. You establish the connection once, and then both sides can send data at any time, without any extra ceremony.
\n\nHow it works:
\n- \n
- The client initiates a handshake via HTTP. \n
- The server switches the protocol to ws:// or wss://. \n
- A permanent bidirectional connection is established. \n
- Data is transmitted in frames — lightweight and fast. \n
Client-side code (JavaScript):
\nconst socket = new WebSocket('wss://example.com/chat');\n\n// When the connection is open\nsocket.onopen = function() {\n console.log('Connection established');\n socket.send(JSON.stringify({ type: 'greeting', text: 'Hello, server!' }));\n};\n\n// When a message arrives\nsocket.onmessage = function(event) {\n const data = JSON.parse(event.data);\n console.log('Message from server:', data);\n};\n\n// On error\nsocket.onerror = function(error) {\n console.error('WebSocket error:', error);\n};\n\n// On close\nsocket.onclose = function(event) {\n console.log('Connection closed. Code:', even