Search code examples
javascriptfor-loopwait

Javascript: Waiting for one (or multiple) condition in For Loop


I want to check a condition for k times for a value to be true, inside a For loop, each time I want to wait 2 seconds, after that I want to go next iteration of the for a loop. For example, I tried something like below -

var k = 0;
for (let i = 0; i < B.length; i++) {
  setTimeout(function F_stTimer() {
      if (B[i].innerText === "S") {
        var A = "True"; //just for example
        if (A === true && k == 0) {
          // Do something
          k = k + 1;
          i = i - 1; // so , I can check the ith element again once start the loop again
        } //if
        else if (A === true && k > 0 && k < 5) { //checking 5 times for A to be false

          k = k + 1;

        }, i * 2000);
      i = i - 1;
    } //if
    else if (A === true && k == 5) {
      k = 0;
    } //if

  } // if 
}, 5000);
} // i loop

But the above type of code is not working because I do not change when it is inside setTimeout.

Anyway, can anyone help me with the problem I have?

One does not need to follow the way I mentioned above, what I want to do is-

check a condition for k times for a value to be true, inside a For loop, each time I want wait t seconds (duration of each delay/interval of delay), after that, I want to go next iteration of the for a loop.

Plz comment for further clarification.


Solution

  • You could write a function that takes two arguments:

    1. howManyTimes - number of times you want to iterate

    2. howOften - in what intervals you want to do the check (in milliseconds)

    function checkInIntervals(howManyTimes, howOften) {
    	var counter = 0;
      
    	var interval = setInterval(function() {
            counter++;
            if (counter === howManyTimes) {
        	    clearInterval(interval);
            }
      	    // do something
            console.log(counter, 'iteration')
        }, howOften)
    }
    
    // run the function
    checkInIntervals(10, 2000);

    Inside the interval the counter is incremented and when it's equal the the desired number of iterations, the interval is cleared and the execution stops.