1

I have a counter on my page that is using the following code:

$(window).scroll(function(){    
if ($(window).scrollTop() > 1400) {
    var max = 67;
    incCounter();
    $('#counter').fadeIn(800);
    }

    function incCounter() {
      var currCount = parseInt($('#counter').html());
      $('#counter').html(currCount+1);
      if (currCount+1 != max) {
        setTimeout(incCounter, 20);
      }
}
}

It starts at 0 and then continues without stopping at the maximum value. How do I get it to do so?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
user913304
  • 37
  • 1
  • 8

2 Answers2

2

jsFiddle Demo

The problem was that you kept incrementing the counter even when you found the value to be met. You need to slightly re-organize your function like this:

function incCounter() {
  var currCount = parseInt($('#counter').html());
  if (currCount != max) {
    $('#counter').html(currCount+1);//only increment when possible
    setTimeout(incCounter, 20);
  }
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
1

You never seem to check whether you are at the bottom. It seems to me that you check the scrollTop but even when you reach that you still go into the function and increment the counter.

I suggest you check to see if you are at the bottom and if you are then do not call the incCounter function

This may help. Check if a user has scrolled to the bottom

Oh and you never stop the TimeOut so it's going to keep going.

So

var myInterval = setTimeout(incCounter, 20)

then

window.clearInterval(myInterval)
Community
  • 1
  • 1
griegs
  • 22,624
  • 33
  • 128
  • 205
  • Just to clarify, I want the counter to start at the point where the user scrolls into the div containing it (~1400 px). Since the Max variable is set at 67, it should complete while the user is still viewing the div. – user913304 Apr 07 '13 at 23:26
  • 1
    Ah right. So you will need to, in the incCounter function I think, check to see where the user is and keep the counter going. When you then detect they are no longer in the div, cancel the timeout function. I think the link still applies because you can use it to check where the user is – griegs Apr 07 '13 at 23:31