javascript - setTimeout的机制引起的bug

 mobiledu2502868793 发布于 2022-11-16 10:54

浏览器打开了2个标签页,其中一个标签页A中有如下代码:

`

    var time = 0;
    var i = 0;
    var t = 0;

    function test(){
        i++;
        setTimeout(function(){
            $('body').append('-'+i);
            test();
        },100);
    }

    test(); 
  `

如果我一直停留在这个页面上,程序没有任何问题,会不断的在页面上打印递增的数字 ,但是当我点击另一个标签页B时,标签页A中的代码会停止执行,直到我重新切换到标签页A时,代码又会继续执行。
这个问题不知道要怎么解决,求大神帮忙感激不尽!

PS.经过测试,发现这个问题只有在chrome和firefox才会出现,IE正常。
再PS.上面说的停止执行是我的视觉误判,真实原因如下:
On the Chromium blog, Google said:
In the forthcoming Chrome 11 release, we plan to reduce CPU
consumption even for pages that are using setTimeout and setInterval.
For background tabs, we intend to run each independent timer no more
than once per second. This change has already been implemented in the
Chrome dev channel and canary builds.

解决办法:使用webworker(兼容性不够好)或者使用这个补丁 https://github.com/turuslan/H...

7 个回答
  • 涨姿势了!!!!!

    2022-11-16 13:37 回答
  • webkitfirefox想要补回来这段时间差,可以用visibilitychange事件。

    document.addEventListener('visibilitychange', function(e){
        document.title = !document.hidden ? 'focus' : 'blur';
        // do something
    }, false);
    2022-11-16 13:37 回答
  • 自己在页面切换时记录时间然后按时间间隔补上需要循环执行的次数呗

    2022-11-16 13:37 回答
  • 这是浏览器的保护机制,在非当前 标签页 ,setTimeout 和 setInterval 每秒最多执行一次。

    2022-11-16 13:37 回答
  • 页面挂后台长期不点是可能被内存回收机制处理掉的

    2022-11-16 13:37 回答
  • 完全看不出来你的问题在哪,你的意思是关闭页面A,这个计时器也要继续运作?

    2022-11-16 13:37 回答
  • 参考这里:传送门

    原文:

    Convert background page to event page

    Follow this checklist to convert your extension's (persistent) background page to an event page.

    Add "persistent": false to your manifest as shown above.
    If your extension uses window.setTimeout() or window.setInterval(), switch to using the alarms API instead. DOM-based timers won't be honored if the event page shuts down.
    Similarly, other asynchronous HTML5 APIs like notifications and geolocation will not complete if the event page shuts down. Instead, use equivalent extension APIs, like notifications.
    If your extension uses, extension.getBackgroundPage, switch to runtime.getBackgroundPage instead. The newer method is asynchronous so that it can start the event page if necessary before returning it.

    英语不是特别好,就不做中间翻译了。

    2022-11-16 13:37 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有