仅当选项卡处于活动状态时才运行setTimeout [英] Run setTimeout only when tab is active

查看:109
本文介绍了仅当选项卡处于活动状态时才运行setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法停止 setTimeout(myfunction(),10000); 从页面未激活时开始计数。例如,

Is there a way to stop setTimeout("myfunction()",10000); from counting up when the page isn't active. For instance,


  1. 用户到达某个页面并在那里停留2000毫秒

  2. 用户转到另一个选项卡,打开某个页面。

  3. myfunction()直到他们回来才开火另一个8000毫秒。

  1. A user arrives at a "some page" and stays there for 2000ms
  2. User goes to another tab, leaves "some page" open.
  3. myfunction() doesn't fire until they've come back for another 8000ms.


推荐答案

你走了:

(function() {
    var time = 10000,
        delta = 100,
        tid;

    tid = setInterval(function() {
        if ( window.blurred ) { return; }    
        time -= delta;
        if ( time <= 0 ) {
            clearInterval(tid);
            myFunction(); // time passed - do your work
        }
    }, delta);
})();

window.onblur = function() { window.blurred = true; };
window.onfocus = function() { window.blurred = false; };

现场演示: http://jsfiddle.net/simevidas/J68dJ/3/show/

这篇关于仅当选项卡处于活动状态时才运行setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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