javascript - setTimeout的机制引起的bug

查看:94
本文介绍了javascript - 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...

解决方案

参考这里:传送门

原文:

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.

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

这篇关于javascript - setTimeout的机制引起的bug的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆