How to stop an animated gif from looping

Based on this answer, it's kinda expensive, but it works. Let's say a single loop takes 2 seconds. At a setTimeout after 2 seconds kick in a setInterval, that would reset image source every millisecond:

setTimeout(function() {
    setInterval(function() {
        $('#img1').attr('src',$('#img1').attr('src'))
    },1)
}, 2000)

again, probably just a proof of concept, but here's demo: http://jsfiddle.net/MEaWP/2/


can you find out how long the gif takes to loop once? if so then you can stop the image like this:

pseudocode:

wait until the end of the image (when it is about to loop)
create a canvas element that has a static version of the gif as currently displayed drawn on it
hide gif
display canvas element in a way that makes it look like the gif froze

javascript:

var c = $("canvas")[0];
var w = c.width;
var h = c.height;
var img = $("img")[0];
setTimeout(function () {
    c.getContext('2d').drawImage(img, 0, 0, w, h);
    $(img).hide();
    $(c).show();
},10000);

jsfiddle

edit: I forgot to add reference to the original answer that I took this from, sorry

Stopping GIF Animation Programmatically

that one doesn't address the time factor you need for only one loop

Also, it has been mentioned that this approach is problamatic in certain cases (It actually didn't work when I try it in firefox right now...). so here are a few alternatives:

  1. mentioned by Mark: edit the gif itself to avoid looping. this is the best option if you can. but I've run into cases where it was not an option (like automated generation of images by a third party)

  2. instead of rendering the static image with canvas, keep a static image version and switch to stop looping . this probablyhas most of the problems as the canvas thing


Actually it is possible to make a gif to stop after just one iteration or any specific number of iterations, see an example below (if it is not already stopped), or in jsfiddle.

gif with stops after two iterations

To do that the gif must be created with number of iterations specified. This could be done using Screen to Gif, it allows to open a gif or a bunch of images and edit it frame by frame.

This solution also allows you to reset the animation by imgElem.src = imgElem.src; but this does not work in MS IE/Edge.


I was having the same problem with an animated gif. The solution is rather simple.

  1. Open the Animated gif in Photoshop.

  2. Go to the Window tab and select timeline(if the timeline is not already open).

  3. At the bottom of the timeline panel, you will find an option, which says "Forever". Change that to "Once".

  4. Go to File> Export> Export for Web and save it as a gif.

That should do it.