2016-04-20 52 views
0

即時嘗試創建一個計數器,問題是,即時通訊設法使計數器只有當用戶在窗口中運行,如果用戶離開窗口或另一個分隔符櫃檯應該停止,直到他回來。計數器停止出窗口瀏覽器

這裏是我的代碼:

$(window).blur(function(){ 
console.log("Counter Should Stop"); 
}); 
$(window).focus(function(){ 
window.onload = function(){ 

(function(){ 
    var counter = 10; 

    setInterval(function() { 
    counter--; 
    if (counter >= 0) { 
     span = document.getElementById("count"); 
     span.innerHTML = counter; 
    } 
    // Display 'counter' wherever you want to display it. 
    if (counter === 0) { 
     alert('this is where it happens'); 
     clearInterval(counter); 
    } 

    }, 1000); 

})(); 

} 
}); 

回答

1

你有一些範圍的問題,以及嵌套函數的問題。爲了便於閱讀,以及幫助您調試,我建議將其重構爲每個事件的單獨函數名稱。這也有助於提高可重用性。

這應該做你要找的內容:

(function(){ 
    // your global variables 
    var span = document.getElementById("count"); 
    var counter = 10; 
    var timer; 

    // your helpers 
    var startTimer = function() { 
    // do nothing if timer is already running 
    if (timer) return; 

    timer = setInterval(function() { 
     counter--; 
     if (counter >= 0) { 
     span.innerHTML = counter; 
     } 
     // Display 'counter' wherever you want to display it. 
     if (counter === 0) { 
      alert('this is where it happens'); 
      stopTimer(); 
     } 
    }, 1000); 
    }; 

    var stopTimer = function() { 
    clearInterval(timer); 
    timer = null; 
    }; 

    // your handlers 
    var onBlur = function() { 
    stopTimer(); 
    }; 

    var onFocus = function() { 
    startTimer(); 
    }; 

    var onLoad = function() { 
    startTimer(); 
    }; 


    // assign your handlers 
    $(window).load(onLoad); 
    $(window).blur(onBlur); 
    $(window).focus(onFocus); 

})();