Alexander Mills
Alexander Mills

Reputation: 99980

Create count loop

I have come across this problem and embarassed to say I have never devised a good solution that has left me feeling satisfied -

I want to count to a number and then once the number is reached start counting up from 0 again.

so in JavaScript, we might have

var incr = 0;

if (incr === 50) {
    incr = 0;
}
incr++;

is there a more elegant way to do that, or is this pretty much the only way to do it? I keep thinking there is a way to do it with Math.max or Math.min, but never have figured it out.

Upvotes: 0

Views: 66

Answers (3)

Spaceman
Spaceman

Reputation: 1339

Dont know if this counts. But a simple for and while loop?

var targetNumber = 50;
while(true) // Some condition
{
    for (var i = 0; i < targetNumber; i++)
    {
        // Do stuff
    }
}

Upvotes: -1

Nyavro
Nyavro

Reputation: 8866

You can use mod by 50

incr %= 50

Upvotes: 2

Linus Oleander
Linus Oleander

Reputation: 18127

Use modulus % for this.

incr++ % 50;

Upvotes: 1

Related Questions