【问题标题】:A code is executed faster in the activated tab [duplicate]在激活的选项卡中执行代码更快[重复]
【发布时间】:2022-08-24 06:05:09
【问题描述】:

此代码旋转网站图标:

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);

它的问题是,当浏览器中的一个选项卡被激活时,旋转比激活另一个选项卡时更快。换句话说,如果我们的网站是在浏览器的当前标签页中打开的,那么旋转是相当流畅的。当另一个选项卡被激活时,旋转速度要慢得多。

我已经检查了 Chrome 和 Firefox。这可能是什么原因?

标签: javascript


【解决方案1】:

为此目的使用requestAnimationFrame 函数。

非活动选项卡中计时器功能的延迟是故意的。你可以在 MDN 中找到:

从后台减少负载(和相关的电池使用) 选项卡,浏览器将在非活动选项卡中强制执行最小超时延迟。

如果您需要恒定的动画速度,则需要在浏览器重新绘制时完成。

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

如果您需要更改速度,请使用外部计数器。

【讨论】:

  • 我希望动画完全暂停在非活动标签中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-26
  • 1970-01-01
相关资源
最近更新 更多