2013-08-24 95 views
0

下面的代碼工作正常,但計時器會低於0即,-1,-2,...等如何添加暫停和恢復的計時器事件在我的代碼

如何自動暫停當瀏覽器在後臺並在我們使用它時恢復計時器?

我的計時器僅在單擊圖像時啓動。

<script type="text/javascript"> 
/*<![CDATA[*/ 

var zxcMatch={ 

Reset:function(id){ 
    var o=this[id],z0=0; 
    if (o){ 
    clearTimeout(o.to); 
    o.time[1]=null; 
    for (;z0<o.imgs.length;z0++){ 
    o.imgs[z0].style.visibility='visible'; 
    } 
    o.cnt=z0/2; 
    o.lst=null; 
    } 
}, 

init:function(o){ 
    var id=o.ParentID,imgs=document.getElementById(id).getElementsByTagName('IMG'),z0=0; 
    o.imgs=imgs; 
    for (;z0<imgs.length;z0++){ 
    this.addevt(imgs[z0],'mouseup','match',o,imgs[z0]); 
    } 
    o.time=[typeof(o.Timer)=='function'?o.Timer:null]; 
    o.cnt=z0/2; 
    this[id]=o; 
}, 

match:function(o,img){ 
    if (o.time[0]&&!o.time[1]){ 
    o.time[1]=new Date(); 
    o.to=setInterval(function(){ o.time[0](o,Math.floor((new Date()-o.time[1])/1000)); },1000); 
    } 
    if (!o.lst){ 
    o.lst=img; 
    } 
    else { 
    if (o.lst.className==img.className&&o.lst!=img){ 
    img.style.visibility=o.lst.style.visibility='hidden'; 
    o.cnt--; 
    if (o.cnt==0){ 
    clearTimeout(o.to); 
    o.time[1]=null; 
    o.Complete(); 
    } 
    } 
    else { 
    alert('try again'); 
    } 
    o.lst=null; 
    } 
}, 

addevt:function(o,t,f,p,p1){ 
    var oop=this; 
    o.addEventListener?o.addEventListener(t,function(e){ return oop[f](p,p1);},false):o.attachEvent?o.attachEvent('on'+t,function(e){ return oop[f](p,p1); }):null; 
} 


} 

zxcMatch.init({ 
ParentID:'match-holder', 
Timer:function(o,sec){ 
    document.getElementById('count').innerHTML=30-sec; 
    if (sec>29){ 
    alert('Time Out'); 

    } 
}, 
Complete:function(){ 
// window.top.location='http://www.stackoverflow.com/'; 
} 
}); 
/*]]>*/ 
</script> 
<span id="count" ></span> 

回答

0

如果用戶專注於文檔或不使用這個你可以聽:

if (/*@[email protected]*/false) { // check for Internet Explorer 
    document.onfocusin = onFocus; 
    document.onfocusout = onBlur; 
} else { 
    window.onfocus = onFocus; 
    window.onblur = onBlur; 
} 

下面是我如何使用上面的例子:

var windowIsFocused = true; 
var lastTimeStamp = 0; 
function onFocus(event){ 
    if(!event || event.lastTimeStamp < lastTimeStamp - 10) return; //prevent double counting in safari and chrome 
    lastTimeStamp=event.lastTimeStamp||0; 
    windowIsFocused=true; 
    //Add timer resume here 
}; 
function onBlur(event){ 
    if(!event || event.lastTimeStamp < lastTimeStamp - 10) return; //prevent double counting in safari and chrome 
    lastTimeStamp=event.lastTimeStamp||0; 
    windowIsFocused=false; 
    //Add timer pause here 
} 
if (/*@[email protected]*/false) { // check for Internet Explorer 
    document.onfocusin = onFocus; 
    document.onfocusout = onBlur; 
} else { 
    window.onfocus = onFocus; 
    window.onblur = onBlur; 
} 
相關問題