猿问

setTimeout的机制引起的bug

浏览器打开了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...


慕田峪7331174
浏览 734回答 1
1回答

鸿蒙传说

参考这里:传送门原文:Convert background page to event pageFollow 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.英语不是特别好,就不做中间翻译了。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答