What's the best approach to display a backend timer on the frontend in Java?

I’m working on a Java application where I need to show a running timer on the user interface. My backend has a GameSession class with a method called getCurrentTime() that returns the time that has passed since starting, measured in milliseconds.

The frontend needs to display this timer value and keep it updated. I’m wondering what would be the most efficient way to keep both sides in sync.

One option I considered is creating a background thread that calls gameSession.getCurrentTime() every second to refresh the display. However, this feels like it might not be the most elegant solution.

I also thought about adding timing logic directly in the frontend code, but that seems wrong since it would mix business logic with presentation logic.

My current Timer utility class doesn’t have any callback functionality built in.

What would be the recommended pattern for this kind of scenario?

Try a WebSocket connection between your frontend and backend. Skip the constant polling - your backend pushes timer updates at regular intervals, and the frontend just receives and displays them. I’ve used this exact setup for real-time updates and it works great. WebSocket keeps a persistent connection open, so your GameSession can broadcast time updates without overhead. Set up a scheduled task in your backend that calls getCurrentTime() and pushes it through the WebSocket. Way less network traffic than HTTP polling, and users get snappier updates. Your frontend stays focused on just showing the data while your backend handles all the timing logic.

just use setInterval in javascript on the frontend. grab the start timestamp from your backend when the game begins, then let js count locally. way simpler than websockets for this and you won’t hammer your server. sync it every now and then if ur worried about drift.