计数器停在窗口浏览器外面

时间:2016-04-20 19:04:18

标签: javascript jquery

我试图创建一个计数器,问题是我试图让计数器只在用户在窗口时运行,如果用户离开窗口或到另一个分隔符,计数器应该停止直到他回来

这是我的代码:

$(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 个答案:

答案 0 :(得分: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);

})();