Pedro
Pedro

Reputation: 1477

Counter stop out of the window browser

im trying to create a counter, the problem is that im trying to make the counter run only if the user is in the window, if the user goes out of the window or to another separator the counter should stop untill he comes back.

Here is my code:

$(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);

})();

}
});

Upvotes: 0

Views: 96

Answers (1)

smaili
smaili

Reputation: 1235

You've got some scoping issues, as well as nested function issues. For readability, as well as helping you debug, I'd recommend refactoring it into separate function names for each event. This also helps promote reusability.

This should do what you're looking for:

(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);

})();

Upvotes: 1

Related Questions