Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

break not work while looping with setTimeout

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);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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; }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading