Search code examples
javascriptnode.jsarraysloopssettimeout

How to loop an array with loop time double the array length/size


how can I loop through an array of character with fixed element in it ( in my case is 4 items in the array) n time (for n can be changed)? I'm trying to make a spinner using setTimeout and \r, and the initial code is:

setTimeout(() => {
  process.stdout.write('\r|   ');
}, 100);

setTimeout(() => {
  process.stdout.write('\r/   ');
}, 300);

setTimeout(() => {
  process.stdout.write('\r-   ');
}, 500);

setTimeout(() => {
  // Need to escape the backslash since it's a special character.
  process.stdout.write('\r\\   '); 
}, 700);

But I want to increase the running time for the spinner, the simpler approach is copying and pasting those line again and increasing the delay time parameter. However, I'm trying to make it shorter by using the loop and come up with this (just testing for the output from array, not yet implementing the setTimeout in the loop):

const char = ['|', '/', '-', '\\'];
// want to repeat the char 2 times for longer run
const nRun = char.length * 2;
for (let i = 0; i < nRun; i++){
  console.log(char[i]);
}

But the array.length is only 4, if I do this, it would output undefined for the 5th->8th time it run through the loop. Is it possible for these codes to be put into a loop?

Thank you in advanced.


Solution

  • You have to use the remainder operator (%) in order to loop in your array like it's a ring:

    const char = ['|', '/', '-', '\\'];
    // want to repeat the char 2 times for longer run
    const nRun = char.length * 2;
    for (let i = 0; i < nRun; i++){
      console.log(char[i % 4]); // <= change here
    }
    

    The remainder operator (%) returns the remainder left over when one operand is divided by a second operand.

    You can learn more about this operator here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder