如果窗口模糊,则暂停Setinterval

时间:2013-02-23 16:27:42

标签: ajax focus setinterval blur

我在这里找到了一个代码,以帮助查找选项卡是否处于活动状态。目标是每10秒调用一次ajax(跨域)URL,以便查找用户在网站上停留多长时间。 找到不同的改编后,我打电话给这里寻求帮助!提前感谢任何解释:)

<script type="text/javascript">
var state='';

(function() {
    var hidden, change, vis = {
            hidden: "visibilitychange",
            mozHidden: "mozvisibilitychange",
            webkitHidden: "webkitvisibilitychange",
            msHidden: "msvisibilitychange",
            oHidden: "ovisibilitychange" /* not currently supported */
        };             
    for (hidden in vis) {
        if (vis.hasOwnProperty(hidden) && hidden in document) {
            change = vis[hidden];
            break;
        }
    }
    if (change)//this is for detecting without  focus, so it works for your second requirement
        document.addEventListener(change, onchange);
    else if (/*@cc_on!@*/false) // IE 9 and lower
        document.onfocusin = document.onfocusout = onchange
    else
        window.onfocus = window.onblur = onchange;

    function onchange (evt) {
        var body = document.body;
        evt = evt || window.event;

        if (evt.type == "focus" || evt.type == "focusin")
       {   
    body.className = "visible";
       state='visible';
        }         else if (evt.type == "blur" || evt.type == "focusout")
        {  body.className = "hidden";     state='';}
            else    {    
            body.className = this[hidden] ? "hidden" : "visible";}
    }

})();

setInterval(function() {
if(state=='visible')
{
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
     if (request.readyState == 4 && request.status == 200) {
        console.log(request.responseText);
     }
  }
request.open('GET', 'http://mywebsite.com.php?v=<?php echo $idvisite;?>', true);
request.send();
}
}, 10000);

</script>

0 个答案:

没有答案