Prevent SMIL animation from pausing when switching between browser tabs

213 Views Asked by At

How to prevent SMIL animation from pausing when switching between browser tabs?

I have SVG clock that is animated using <animatetransform>. When you switch to another tab animation freezes and don't catch up to where it should be. I want this animation to either run smoothly when page is not visible or to pause and catch up when the page is visible again. I can convert this to CSS animation, it doesn't matter.

Here's a simplified code for seconds hand:

HTML:

<svg viewbox="-250 -250 500 500" fill="none" stroke="#000">
<!-- ... -->
  <path id="Sec" stroke="#000" stroke-width="14" d="M0 0v-220">
    <animatetransform fill="freeze" additive="sum" attributename="transform" dur="60s" from="0" repeatcount="indefinite" to="360" type="rotate" />
  </path>
<!-- ... -->
</svg>

JS:

const date = new Date()
const sec = date.getSeconds()
document.getElementById('Sec').setAttribute('transform', `rotate(${(sec * 360 / 60) % 360})`)

I know how to use Page Visibility API to pause things but how to prevent them from doing so is incomprehensible for me.

1

There are 1 best solutions below

0
dziku86 On BEST ANSWER

Ok. I figured that one out.
When the page is hidden the animation is paused with animationsPaused().
When the page is visible again the script:

  1. gets new date
  2. resets animation clock with setCurrentTime(0)
  3. updates <path> transform attribute
  4. starts animation with unpauseAnimations()

HTML:

   <svg id="Watch" viewbox="-250 -250 500 500" fill="none" stroke="#000">
     <!-- ... -->
     <path id="Sec" stroke="#000" stroke-width="14" d="M0 0v-220">
       <animatetransform fill="freeze" additive="sum" attributename="transform" dur="60s" from="0" repeatcount="indefinite" to="360" type="rotate" />
     </path>
     <!-- ... -->
   </svg>

JS:

   const svg = document.getElementById('Watch')
   let date = new Date()
   const watch = () => {
     document.getElementById('Sec').setAttribute('transform', `rotate(${(date.getSeconds() * 360 / 60) % 360})`)
   }
   window.requestIdleCallback(() => watch())
   document.addEventListener('visibilitychange', () => {
     if (document.hidden) svg.pauseAnimations()
     else {
       date = new Date()
       svg.setCurrentTime(0)
       watch()
       svg.unpauseAnimations()
     }
   })