Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reset counter in jQuery function

Ok, this seems pretty basic but I’m stuck.

I’m setting a var outside of the loop, then increment and once the counter reaches a threshold I need to reset it back to 0.

var cnt = 0;
$("ul").each(function(cnt) {
    var ths = $(this),
        tul = ths.attr("id");
        
    cnt = cnt++;
       
    if (cnt == 20) {
        cnt = 0;
    }
...
});

For some reason it keeps incrementing till the end of the look. What am I missing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If cannot be reset to 0 because cnt is the .each(function(cnt) { function’s index argument, and will always be the iterating index. You’re trying to reset something to 0 which in the next loop will again be the index integer.

Depending on what’s the desired (not clear from your question so far) you could simply not use the index attribute:

let cnt = 0;

$("ul").each(function() {
  cnt += 1;
       
  if (cnt === 20) {
    cnt = 0;
  }

   // ...
});

Modulo (reminder) operator

Use the reminder operator % to loop back to 0 once idx becomes 20.
In that case you don’t need the outer variable, but you can use the iterating index attribute instead:

$("ul").each(function(idx) {
  let cnt = idx;
  cnt %= 20;  // Reset to 0 once idx is 20
       

   // ... 
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading