0

happening on safari mainly. The idea is this: animate 4 images one after the other but seconds one image can appear differs.

It works well in firefox but in safari it is very flaky and blinks a lot.

After images are preloaded, the animation should start. First, settimeout is called 0 so that the first image can be loaded asap. then the the ms parameter of settimeout takes in a millisecond value based on the index of the current image.

        var timer = null;
           var index = -1;
           var frame = 0;
           var loop = true;
           var counter = 0;
    var initialPause = 0;
         var imagesDisplayFor = [1000, 2000];
           async function preLoadImages() {
            var frames = imagesDisplayFor.map(async(v, i) => {
              let img = new Image()
              img.onload = function() { return Promise.resolve() }
              img.src =  '../src/assets/'  + i + '.png'
              return img
            })
            await Promise.all(frames)
            reset()
          }
    
            function pauseAnimationFor(fn) {
            const wait = index === -1 ? initialPause : imagesDisplayFor[index];
            clearTimeout(timer)
            timer = setTimeout(fn, wait)
          }
          function reset(){
              index = -1;
              animate();
          }
        function  animate() {
    
            pauseAnimationFor(() => {
              if (this.index < 1) {
                index++
                var src = '../src/assets/'  + index + '.png';
                document.getElementById("imagePlaceHolder").src = src;
                animate()
              }else{
                  reset();
              }
            })
          }
    preLoadImages().then(done=>{
        animate();
    })
    <html lang="en">
      <head>
      </head>
      <body>
        <img id="imagePlaceHolder"/>
     
      </body>
    </html>
Udhay Titus
  • 5,761
  • 4
  • 23
  • 41
  • did you try replacing setTimeout with requestAnimationFrame ? see https://stackoverflow.com/questions/38709923/why-is-requestanimationframe-better-than-setinterval-or-settimeout – 36ve Mar 24 '21 at 11:26
  • @36ve thanks. Wasn't ware of it but is there a way to make 0.png appear for 10 seconds then be replaced by 1.png which stays for 5 seconds.... it looks like this is a smooth transition for predefined milliseconds for each? –  Mar 24 '21 at 11:34

1 Answers1

0

Try using Window.requestAnimationFrame(). It is more precise then setTimeout and is synced to browsers repaint.

Things to keep in mind:

  • You don't have control over fps (which is usually 60), so you need to use first argument in callback to know how much time passed
  • you need to call requestAnimationFrame() each time you are ready to paint something new
Kuba Kuba
  • 11
  • 2