Creating a reliable cross-tab timer with backend validation

Hey everyone! I’m working on a project where I need to build a timer that keeps ticking even when the user switches tabs. The goal is to save the elapsed time in a database when the user stops the timer.

I’ve run into a couple of challenges:

  1. The timer gets wonky when the tab isn’t active. Looks like browsers don’t prioritize inactive tabs.

  2. I’m not sure how to check the time on the server side. I thought about using AJAX to ping the server every now and then, but I’m stumped on how to track time in PHP. Is that even doable?

I’m cool with ditching old browsers, but I want it to work on all the new ones (except Edge, because reasons).

Any ideas on how to tackle this? I’d love to hear your thoughts on making this timer rock-solid across tabs and validated by the backend. Thanks a bunch!

yo, web workers are cool but they can be tricky. maybe try using the Page Visibility API to detect when the tab goes inactive? then u could adjust ur timer logic. for server validation, store start timestamp and compare w/ current time on stop. just a thought!

hey, have u considered web workers? they run in background even when tabs are inactive. on server side, u could save the start time in db and calc elapsed time on stop. any other approaches u thought about?

I’ve encountered similar challenges with cross-tab timers. One effective approach is using the localStorage API to store the timer’s start time and updating it periodically. This method persists across tabs and browser sessions. For server-side validation, you can send the start and end timestamps to the server when the timer stops. The server can then calculate the elapsed time, compare it with the client-side value, and store the verified result in the database. This approach provides a good balance between client-side responsiveness and server-side accuracy, while also addressing the inactive tab issue.