Pomodoro Clock - Updating time when window not focussed

Pomodoro Clock - Updating time when window not focussed
0.0 0

#1

Hey guys,

So I thought I had finished the code for my Pomodoro Clock until I realised that if you don’t have the window focussed then it doesn’t continue counting. I’m currently using p5.js which periodically updates within draw() (I’ve also used setInterval).

I’ve experimented by using Date.now() and calculating the difference, all sorts. But they all have the same issue that when you alt-tab away from the page then it stops.

I thought that if I could capture the event of the user changing window then I could just count the time between it and update it when they return, but that would mean the alarm still wouldn’t activate if you don’t focus the window.

Is this really that complicated to do? It feels like it shouldn’t be!

(Please open the link, the preview doesn’t seem to work :))

SOLVED, solution here:
I fixed the setInterval issue. Firefox and Chrome set intervals to a limit of 1000ms for when the window is not in focus. Therefore, if you adjust your code to work in 1000ms intervals (mine was 100ms) then it should be fine. For example I was -= 0.01 at 100ms, but changing it to 0.1 at 1000ms means the code now works just fine. (I think that was it, anyway :))


#2

yeah i’ve ran into the same problem too.

what it is i think the libary you are using p5.js, uses requestAnimationFrame() function under the hood, and so when you change tab for some reason requestAnimationFrame no longer updates the page.

to simplify things you could use setInterval. Its not like you need to show millisecond response time.

or to get around this though, you could create a render function

function render() {
  // TODO update seconds, minutes left, title
  
  if (document.hidden) { // in another tab
    setTimeout(render, 500) // 500ms
    return
  }
  requestAnimationFrame(render)
}

you may also want to make a boolean to set to stop the render function calling itself.


#3

Hey, thanks for taking the time to reply!

I tried using setInterval but because I’m updating the text with the draw() function it won’t update it unless it’s on the page. I thought it would be easier to use p5 but starting to regret it slightly ha.

As to the other suggestion, I am not quite sure what a render function is :disappointed_relieved:

//

Solution for anyone that needs it
I fixed the setInterval issue. Firefox and Chrome set intervals to a limit of 1000ms for when the window is not in focus. Therefore, if you adjust your code to work in 1000ms intervals (mine was 100ms) then it should be fine. For example I was -= 0.01 at 100ms, but changing it to 0.1 at 1000ms means the code now works just fine. (I think that was it, anyway :))