javascript - 当窗口未聚焦时 setTimeout() 是否有问题?

标签 javascript jquery settimeout

我正在开发一个网站,该网站使用 setTimeout() 在我的网站上制作带有横幅的“幻灯片”。一切正常,我将延迟设置为 10 秒。只有当我切换窗口/选项卡并执行其他操作时才会出现此问题。当我回来时,该函数运行了很多次我(假设) catch 什么的。问题是,我的屏幕开始反复闪烁,显示所有横幅淡入淡出。

有什么解决方案吗?我在 Google Chrome 中注意到了这一点,我也知道它发生在 Firefox 中。不确定 IE。

编辑

这是我正在处理的片段。遗憾的是,它是一个非常大的脚本的一部分,并且连接到一个非常复杂的 HTML 文件。

我希望你至少能了解这里发生了什么:

var lval=0;
var nval=1;
setHead = function(data) {
        lval=nval;
        var index=1;
        $.each(data, function(name,value) {
            if (Math.floor(Math.random()*index+2)==index+1) {
                nval=index;
            }
            if (index==lval) {
                $('.headmaster').find('img').fadeOut('fast');
                //$('.headmaster').css('background-color',value.backgroundcolor);
                $('.headmaster').find('a').attr('href',value.url);
                $('.headmaster').animate({backgroundColor:value.backgroundcolor},'slow',function() {
                    $('.headmaster').find('img').attr('src',value.img);     
                    $('.headmaster').find('img').fadeIn('slow');                                                                        
                });
            }
            index++;
        });
        setTimeout(function() { setHead(data); },10000);
}

arrayGet = function(arr,idx) {
    $.each(arr, function(i,v) {
        if (i==idx) {
            return v    
        }
    });
    return null
}

$(document).ready(function() {  
    $.getJSON('json/intros.json', setHead);
});

我使用 jQuery 制作动画,使用颜色插件淡化颜色。

最佳答案

这可能是因为您使用的是旧版本的 jQuery。也就是说,开发团队已开始使用 requestAnimationFrame API。幸运的是,他们在 1.6.3 中修复了它。这是他们的 blog 的摘录:

No more animation “worm holes”: We had high hopes for the browser’s requestAnimationFrame API when we added support into version 1.6. However, one of the highest-volume complaints we’ve received since then relates to the way requestAnimationFrame acts when a tab is not visible. All the animations initiated when the tab is invisible “stack” and are not executed until the tab is brought back into focus. Then they all animate at warp speed! We’ve removed support for this API (which has no impact on the way you call jQuery’s animation features) and plan to incorporate it into a future version of jQuery.

只需更新到1.6.4 .

关于javascript - 当窗口未聚焦时 setTimeout() 是否有问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7675849/

相关文章:

javascript - 用setTimeout注册的函数什么时候被调用?

angular - setTimeOut() 在 Angular Lifecycle Hooks : ngDoCheck, ngAfterContentChecked, ngAfterViewChecked 中重复

javascript - 在经过一段时间或满足条件后运行代码

javascript - 如何按顺序检索特定 DOM 元素的所有 index() 值

javascript - 检测组合字符以忽略其中的一些

javascript - 如何根据 className 删除 fullCalendar 上的事件

jquery - 在 JQuery 中使用 Load() 获取 XML 属性

jQuery 插件问题 - 使用 JSON 数据填充选择选项

javascript - 尝试对 HTML 错误使用 textContent 时出错。 "Unable to set property ' textContent' of undefined"

javascript - 如果存在则附加 url 参数,如果不存在则添加 jQuery