Search code examples
javascriptloopsinfinity

I need to create an infinite loop


For my purpose I need to create loop where one variable is looping in this way: 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1...

It's look simple but more than hour I wonder how to do it. My purpose is moving the star in this way

*....
.*...
..*..
...*.
....*
...*.
..*..
.*...
*....
*....
.*...
..*..
...*.
....*

Solution

  • You can use the following code to generate the number pattern that you require. However, you wont be able to run it infinitely since it will crash the browser.

    If you want to test, I have added instructions for making the loop infinite.

    For you requirement, a larger value for rep variable will be enough.

    let min = 0; // Start/min value
    let max = 4; // Max value
    let dir = 1; // Count direction (+1/-1)
    
    let counter = min; // Your counter variable
    
    let rep = 24; // Remove this line and change condition inside while to true for infinite loop
    
    do {
      console.log(counter);
    
      dir = counter===max?-1:counter===min?1:dir;
      counter+=dir;
    } while (rep-->0); // Change this expression to true for infinite loop