A WebSocket is a single connection between a browser and a server that stays open, so either side can send a message the moment it has something to say. It is how chat apps, live scores and multiplayer games stay up to date without the page asking the server for news every few seconds.
Why asking again and again falls short
Ordinary HTTP works one way round: the client asks, the server answers, and the exchange is over. The server can't speak first. If your page shows a live feed (new messages, new orders, new tuna arriving at the harbour), it has to find out about changes somehow.
The simplest fix is polling: ask on a timer.
setInterval(async () => {
const res = await fetch("/api/tuna/latest");
const tuna = await res.json();
render(tuna);
}, 3000);It works, but it has two costs. Most of those requests come back with nothing new, and every one of them carries full HTTP headers, cookies and, without a reused connection, a fresh handshake. And an update that lands just after a poll waits until the next one, so 'live' really means 'up to three seconds late'. Shorten the interval to cut the delay and you multiply the wasted requests.
Long polling improves on this: the server holds each request open until it has something to send, then the client immediately asks again. It cuts the delay, but it is still one request per update, and the server only ever replies to a question. WebSockets remove the question altogether.
Wondering how this was made? How we make these