0

I have some javascript that crunches some numbers and draws to an HTML5 canvas, creating an animation. When the canvas isn't visible, the expensive and continuous number crunching / drawing is pointless.

So, when the user can't see the canvas (e.g. because they switched tabs or minimized the browser or scrolled down or various other possibilities), I'd like to put a hold on the computation.

In javascript, what's a good way to pause a periodic timer when a canvas isn't visible to the user? (And resume the timer when the canvas is visible again.)

Craig Gidney
  • 17,763
  • 5
  • 68
  • 136
  • possible help : See scroll position http://stackoverflow.com/questions/5036850/how-to-detect-page-scroll-to-a-certain-point-in-jquery – phenxd Mar 08 '16 at 20:00
  • possible help : Pause setInterval http://stackoverflow.com/questions/7279567/how-do-i-stop-a-window-setinterval-in-javascript – phenxd Mar 08 '16 at 20:01

1 Answers1

2

In your other-browser-tab-focused scenario, requestAnimationFrame is ideal -- it auto-pauses its loop on tab blur and auto-resumes on tab focus.

In your scroll-canvas-offscreen scenario you can test your canvas's .scrollTop (with & without .height) vs the window's .scrollTop (with & without height).

To get the benefit of both test, put the .scrollTop test inside the requestAnimationFrame loop.

Craig Gidney
  • 17,763
  • 5
  • 68
  • 136
markE
  • 102,905
  • 11
  • 164
  • 176