Search code examples
javascriptfor-loopsettimeout

How do I have multiple set timeouts running at once?


This is more of a question on how I should approach my problem, and not what code to use. this is the general framework/simplification of my code. I can provide the actual code if needed. question is below, it is similar to the last question I asked as it is part of the same system that isn't working:


for (i = 0; i < 10; i++) {
  var amt = 0;

  function checktime() {
    console.log(amt + " / " + i);
    amt++;

    if (amt <= 5) {
      setTimeout(checktime, 3000);
    }
  }

  checktime();
}

I want it to have all the set timeouts running at once, for each i. the console results in 0 / 0

0 / 1

0 / 2

...

0 / 8

0 / 9

1 / 10

2 / 10

3 / 10

4 / 10

...

13 / 10

14 / 10

I'd like it to look like this:

0/0

0/1

0/2

0/3

...

0/9

1/0

1/1

...

5/9

5/10

sorry for the long question, but how would I go about doing this?


Solution

  • Have a function inside checktime that runs a loop. Set up your variables, and then pass the count variable into the inner function again with your setTimout.

    function checktime() {
    
      // Set the amt variable to zero
      let amt = 0;
    
      // Set count to zero if it doesn't exist
      function loop(count = 0) {
    
        // Log the new data
        console.log(`${amt}/${count}`);
    
        // Increase the count
        ++count;
    
        // If count hits 10 reset the count
        // and increase the amt variable
        if (count === 10) {
          count = 0;
          ++amt;
        }
    
        // Call the loop function again and pass in the new count
        // as a parameter
        setTimeout(loop, 1000, count);
    
      }
    
      loop();
    
    }
    
    checktime();