how to detect when a gif has played once using javascript?

i was wondering if it was possible to detect when a gif has reached its loop point using javascript, to emulate the preloaders of flash content
currently, i have a script to detect when the video is loaded that runs every few frames (taken from here). i was wondering if there was a way to run this every time the gif has ended? i would prefer to not use timeouts if possible, due to wanting to reuse code.

right now, the video is automatically played when it has finished loading, no matter where the gif is

current javascript:

 const videoElement = document.getElementById('video');
 const preloader = document.getElementById('preloader');

 videoElement.addEventListener('loadeddata', (e) => {
 //Video should now be loaded but we can add a second check

 if(videoElement.readyState >= 3){
     console.log("video's done loading");
     preloader.style.display = 'none'
 }

 });

example

  • I don’t think that this is possible. Animated gifs don’t expose any special properties or events via the img tag (or any other tag that I know of) which would allow code to run when a loop was complete.

    – 




  • Why is the gif so special? Can you make an animation in another format that you could control programmatically?

    – 

  • @Kalnode the gif isn’t really special really, i’m only using a gif because it loads fast and is one of the exportable file formats in adobe animate. i’ll try to include an exported html/js document in place of the gif, and get back on if it worked or not

    – 

  • You could set a timeout equal to the gif duration.

    – 

  • Can you use a CSS animation instead? Then you have full control.

    – 

Detecting the end of a loop or single playback of a non-looping GIF is no longer supported in browsers. IIRC there was way of detecting the end of the loop in vintage browsers such as Netscape 3 from the late 1990’s, but somehow got dropped by later browser versions.

A potential solution would be to convert the GIF to a video format suitable for the web in a video editor, play it once (without controls or looping) in a <video> element and use the end event fired on the first video to start the second.

Leave a Comment