I have built a Pomodoro clock in ReactJS, which involves using setInterval
(or setTimeout
), but when I ran it to follow the sessions/breaks patterns, I discovered that at the end of a 90 minutes session on my mobile clock, there was a lag of about 30 minutes in my Pomodoro app. That is, there was a delay of 30 minutes!!
After a little research I discovered that setInterval
doesn't fire exactly at the specific interval you specify, and it tends to drift depending on the CPU load, and these drifts accumulate to make a significant delay in the long run.
A solution to this problem that I came across is the self-adjusting timers that use Date.now()
method to account for the drift in the recursive setTimeout
function.
However, in the process, I came to also know that when a tab in Google chrome is inactive, then even the self-adjusting timers drift because of the way processes are scheduled in the CPU (inactive tabs probably means nothing important to process).
For me this poses a problem, because I would like to run my Pomodoro clock in one tab, and go and work on another tab.
My question is: how can I solve this inactive browser's tab problem to create an accurate timer in JavaScript?