I learned about game loops before web development, and I'm wondering how a page stays responsive to clicks and scrolling. Is something checking the mouse and redrawing the page every frame, or does the page just wait until an event happens?
Does a web page have a game loop running underneath?
Answers
The browser is a bit like the engine in this comparison. It handles input, layout, drawing and event delivery, while page code plugs into that machinery by registering handlers for things like clicks.
There is a loop involved in processing events, but that doesn't mean your page's JavaScript checks the mouse on every tick. When there's no work ready, the browser can wait rather than repeatedly running an empty check. A click can cause an event to be queued, and the handler runs when the browser processes it.
Reply to this answer
Redrawing is separate from checking for input. A browser can keep showing the existing page without your code drawing it every frame. It updates what needs updating when things change, such as scrolling, a style change or an animation.
If you do want a frame-based animation, JavaScript can use requestAnimationFrame to ask the browser to call a function before a repaint. That feels more like a game loop, but a simple page doesn't have to set one up.
Reply to this answer
A button and a clickable sprite are similar at a high level: both have a visible area and can trigger a response. But an HTML button comes with built-in behavior, including keyboard interaction, so it isn't just an image being checked for mouse overlap.
A click might update part of the current page or navigate to another page. Either way, the browser handles a lot of the input and display work that a game might implement differently.
Reply to this answer
There's also a client and server distinction here. The browser can request a page from a server, but the server doesn't automatically receive every click or scroll after sending it. The page has to make another request or use a connection to communicate that activity.
Even a simple page with no custom JavaScript can respond to some input because the browser provides behavior for elements like links and buttons.
Reply to this answer
Add your answer
Answers are reviewed before publication.
!!turnip.truce:
So the page can stay open even when none of its JavaScript is actively running?
hatchback_hypothesis:
Yes. The browser keeps the page's state around, and JavaScript runs again when there's work to do, such as an event handler or a timer callback.