Is there a way to display the number of times an animated gif loops? For example you land on a page with an animated gif and when that gif loops fully through its animation one time, a 1 is displayed. Than that number increases by 1 everytime the gif fully loops. Forever.
Thanks for any insight!
I calculate the duration time of the gif and then setInterval. My gif is 15 seconds long.
const gif = document.getElementById("gif");
gifLoopCounterInit(gif.src);
function gifLoopCounterInit(fileSrc) {
var request = new XMLHttpRequest();
request.open('GET', fileSrc, true);
request.responseType = 'arraybuffer';
request.addEventListener('load', async function () {
calcDurationGif(request.response).then(function (duration) {
const loopCounter = document.getElementById("loop-counter");
setInterval(function () {
loopCounter.innerHTML++;
}, duration * 1000);
});
});
request.send();
}
function calcDurationGif(file) {
return new Promise((resolve, reject) => {
try {
let arr = new Uint8Array(file);
let duration = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i] == 0x21
&& arr[i + 1] == 0xF9
&& arr[i + 2] == 0x04
&& arr[i + 7] == 0x00) {
const delay = (arr[i + 5] << 8) | (arr[i + 4] & 0xFF)
duration += delay < 2 ? 10 : delay;
}
}
console.log(duration / 100);
resolve(duration / 100);
} catch (e) {
reject(e);
}
});
}
<img id="gif" src="https://c.tenor.com/AeFQKHQFFq8AAAAd/gif-art.gif" alt="">
<p>Loops : <span id="loop-counter">0</span> </p>