Skip to content
Advertisement

How to pause for loop and then continue looping

Currently, I am trying to build a function that does the following thing:

  • First click: 1, 2, 3, 4, 5, 6, 7

  • Second click: 8

  • Third click: 9

JavaScript

But in the snippet the code does this now:

  • First click 1, 2, 3, 4, 5, 6, 7
  • Second click 1, 2, 3, 4, 5, 6, 7, 8
  • Third click 1, 2, 3, 4, 5, 6, 7, 8, 9

How can I only add one index when I have a second or third click.

Advertisement

Answer

You have to save the last count i to prevent the loop to start from 0 everytime.

If you want to output the first 7 numbers inline you have to call console.log () after the for loop. But you can feed a string in the loop for the final output. (you can use a simple ternary operator to prepend the comma only if its not the first loop)

Working example: (simplified for demonstration)

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement