How to pause for loop and then continue looping

Tags: ,



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

import { FC, useState } from 'react';

export const HandOutCards: FC = () => {
  const [count, setCounter] = useState(0);

  function firstHandOut(counter: number) {
    let maxLength = 7;
    for (let i = 0; i < 10; i++) {
      console.log(i);
      if (i === (maxLength + counter)) {
        break;
      }
    }
  }

  const counter = () => {
    setCounter(count + 1);
    firstHandOut(count);
  };

  return (
    <button onClick={counter}>HandOut</button>
  );
};

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.

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)

let counter = 0;
let last_count = 0;
let maxLength = 7;

function firstHandOut() {
  let output = '';
  
  for (let i = last_count + 1; i < 10; i++) {
    output += (i != last_count + 1 ? ', ' : '') + i;
    if ((i === (maxLength + counter))) {
      last_count = i;
      break;
    }
  }
  
  console.log(output);
  counter++;
}
<button type="button" onclick="firstHandOut();">test</button>


Source: stackoverflow