kayee
kayee

Reputation: 340

how to use .each() in javascript to show different counters

I have a javascript function that display a counter. The timer starts at 50% of the total value and when it get to 95% the counter will slow down. This is working fine, but I need to display multiple counters with different values. This is my jsfiddle

html

<span class="counter" data-count="100"></span><br/>
<span class="counter" data-count="200"></span><br/>
<span class="counter" data-count="300"></span><br/>

script

var total=$('.counter').data('count'),
    count=Math.ceil(total/2),//set span to half of total by default
    speed=50,
    ninetyFivePercent = Math.floor(total*.95);

$('span').text(count);

//start counter after 2 seconds
setTimeout(function(){
   counter=setInterval(timer, speed);
},2000);

function timer(){
  count=count+1;

  if (count === ninetyFivePercent+1){
     console.log('at 95%');
     clearInterval(counter);
     speed = 1000;
     counter=setInterval(timer, speed);
  }else if (count === total+1){
     console.log('complete');
     clearInterval(counter);
     return;
  }
    $('.counter').text(count);
}

//$('.counter').each(function(){
//  var total=$(this).data('count');
//  var count= Math.ceil(total/2);
//   var ninetyFivePercent = Math.floor(total*.95);
//  $(this).text(count);    
//});

Upvotes: 2

Views: 93

Answers (1)

jparaya
jparaya

Reputation: 1339

One solution is to use

$('counter').each(function(index, element) {
    // here you declare local variables and functions.
}

You can use almost all of your code. The only difference is that the variables and functions must be local, inside de function.

Check http://jsfiddle.net/3eegzfaa/2/

One more thing: try to use var myVariable to declare variables. Maybe you can use Sublime Text 3 and the jslint plugin for online javascript syntax checking. It's not related with your problem, but it's a good practice when you code in javacript.

Greetings!

Upvotes: 2

Related Questions