-3

So I have created a while loop that runs many times (10000-20000) before it stops. I'm trying to count exactly how many times it loops before it stops.

I've tired something like:

let i = 0;

while (i < 20000) {
  i++;
  console.log(i);
}

But incrementing within the loop is not useful because the program will print all the values. Example output:

1
2
3
...
20000

I don't need all these values. I just need the final value, in this case, 20000.

Is there no way to ONLY print the number of times it runs instead of incrementing every single time it runs??

u-ways
  • 6,136
  • 5
  • 31
  • 47
lansXp
  • 13
  • 1
  • 6
  • Post a code snippet so we can understand the problem better – Pavlo Aug 11 '18 at 15:32
  • You don't have to print counter everytime loop iterates. Do it in the last when while loop finishes. – Helping hand Aug 11 '18 at 15:32
  • 4
    That's not that many iterations and definitely should not crash due to incrementing a counter. Try to provide a [mcve], so that others may try and help you. – Ilja Everilä Aug 11 '18 at 15:32
  • Exactly *what* are you incrementing? Please show some basic code. Counting is the only way to know how many iterations have passed – Hans Kesting Aug 11 '18 at 15:33

2 Answers2

3

You can just log count when the loop finish:

let count = 0;

while (count < 200000) {
  // ...
  count++;
}

console.log(count)
u-ways
  • 6,136
  • 5
  • 31
  • 47
  • You are just incrementing. I dont want that. I wanna know how many times my while loop runs without having to increment and print out every single incremented value to the console which just crashes the program. Is there no way to just get the final result, for example if it runs 14000 times, just print out 14000 and not 13999,13998,13997...1 – lansXp Aug 11 '18 at 21:45
  • i tried it but i dont get anything printed to the console... – lansXp Aug 11 '18 at 22:15
  • 1
    I finally got it to work.. SOryy guys, i was using codecademy to print it to the console. thats why it didnt work.. – lansXp Aug 11 '18 at 22:18
0

With the risk of being irrelevant, i can think of 3 simple ways:

  1. Use the Javascript debugger from developer tools (i guess you are talking about client-side javascript)
  2. Print a message at each iteration, and store the log to a file. The you can count the number of lines (= iterations number) of the file. See How to save the output of a console.log(object) to a file?
  3. Use a try - catch statement and print the counter inside the catch statement

I hope it helps. My understanding is that it does not crash because of the counter, but it crashes anyway.

curi0uz_k0d3r
  • 505
  • 2
  • 9