-1

This code rotates favicon:

function removeAllIcons() {
    var allIcons = document.querySelectorAll("link[rel='icon']");
    for (let i = 0; i < allIcons.length; i++) {
        allIcons[i].remove();
    }
}

removeAllIcons();

var favicon_images = [
                    '/n-static/img/animated-favicon/tmp-0.gif',
                    '/n-static/img/animated-favicon/tmp-1.gif',
                    '/n-static/img/animated-favicon/tmp-2.gif',
                    '/n-static/img/animated-favicon/tmp-3.gif',
                    '/n-static/img/animated-favicon/tmp-4.gif',
                    '/n-static/img/animated-favicon/tmp-5.gif',
                    '/n-static/img/animated-favicon/tmp-6.gif',
                    '/n-static/img/animated-favicon/tmp-7.gif',
                ];
var image_counter = 0; // To keep track of the current image

setInterval(function() {            
    // Remove if favicon exist.
    if(document.querySelector("link[rel='icon']") !== null) {
        document.querySelector("link[rel='icon']").remove();
    }
    // Add new favicon image
    document.querySelector("head").insertAdjacentHTML('beforeend', '<link rel="icon" href="' + favicon_images[image_counter] + '" type="image/gif">');
    
    // If last image then goto first image
    // Else go to next image    
    if(image_counter == favicon_images.length -1)
        image_counter = 0;
    else
        image_counter++;
}, 200);

The problem with it is that when a tab in the browser is activated, then rotation is faster than when another tab is activated. In other words, if our web site is open in the current tab of the browser, the rotation is rather smooth. When another tab is activated, the rotation is much slower.

I have checked in Chrome and Firefox. What might be the reason for this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Kifsif
  • 3,477
  • 10
  • 36
  • 45

1 Answers1

1

Use the requestAnimationFrame function for this purpose.

The delay of timer functions in inactive tabs is intentional. You can find in MDN that:

To reduce the load (and associated battery usage) from background tabs, browsers will enforce a minimum timeout delay in inactive tabs.

If you need a constant speed for your animation, it needs to be done when the browser repaints.

requestAnimationFrame(function() {            
    // Remove if favicon exist.
    if(document.querySelector("link[rel='icon']") !== null) {
        document.querySelector("link[rel='icon']").remove();
    }
    ...
    ...

Use an external counter if you need to change the speed.

Charlie
  • 22,886
  • 11
  • 59
  • 90