-1

I'm looping over an array using a "for" loop. I need to go through the loop at 2 second intervals. Need to stop the loop if condition is met. but I can't stop the loop because it has "setTimeout".

let selects = [1,2,3,4,5,6,7,8,9];

for (let j =0; j < selects.length; j++) {
    task(j);
    if (j===5) { break; }
}

function task(i) {
    let tasker = setTimeout(function() {
      
      console.log("loop " + i)
        
    }, 2000 * i);
}
Sercan Aslan
  • 273
  • 3
  • 12
  • 3
    You should be using `j==5` or `j===5`, single `=` is for assignment, and in your case evaluates to `5` which is always truthy – Nick Parsons Oct 16 '22 at 11:37
  • 2
    You're probably better off running your loop until `j <= 5` instead of `j < selects.length`, or using `setInterval()`. – Nick Parsons Oct 16 '22 at 11:38
  • 1
    With your new edit it's unclear what you're asking exactly. The loop now stops at 5, is this not what you're after, and what do you expect instead? – Nick Parsons Oct 16 '22 at 11:54

1 Answers1

1

You are assigning a value to j, You need to use === or == instead of =

for (let j =0; j < selects.length; j++) {
    task(j);
    if (j === 5) { break; }
}
SamHoque
  • 2,978
  • 2
  • 13
  • 43