How to Stop a JavaScript for Loop

How to stop a JavaScript for loop?

To stop a for loop early in JavaScript, you use break:

var remSize = [], 
szString,
remData,
remIndex,
i;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // Set a default if we don't find it
for (i = 0; i < remSize.length; i++) {
// I'm looking for the index i, when the condition is true
if (remSize[i].size === remData.size) {
remIndex = i;
break; // <=== breaks out of the loop early
}
}

If you're in an ES2015 (aka ES6) environment, for this specific use case, you can use Array's findIndex (to find the entry's index) or find (to find the entry itself), both of which can be shimmed/polyfilled:

var remSize = [], 
szString,
remData,
remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = remSize.findIndex(function(entry) {
return entry.size === remData.size;
});

find stops the first time the callback returns a truthy value, returning the element that the callback returned the truthy value for (returns undefined if the callback never returns a truthy value):

var remSize = [], 
szString,
remData,
remEntry;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remEntry = remSize.find(function(entry) {
return entry.size === remData.size;
});

findIndex stops the first time the callback returns a truthy value, returning the index of the element instead of the element; it returns -1 if the callback never returns a truthy value.

If you're using an ES5-compatible environment (or an ES5 shim), you can use the new some function on arrays, which calls a callback until the callback returns a truthy value:

var remSize = [], 
    szString,
    remData,
    remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
remSize.some(function(entry, index) {
    if (entry.size === remData.size) {
        remIndex = index;
        return true; // <== Equivalent of break for `Array#some`
    }
});

If you're using jQuery, you can use jQuery.each to loop through an array; that would look like this:

var remSize = [], 
szString,
remData,
remIndex;

/* ...I assume there's code here putting entries in `remSize` and assigning something to `remData`... */

remIndex = -1; // <== Set a default if we don't find it
jQuery.each(remSize, function(index, entry) {
if (entry.size === remData.size) {
remIndex = index;
return false; // <== Equivalent of break for jQuery.each
}
});

Stop for loop using break on click

The 20 setTimeout functions were called before you even pressed on stop.

One of many ways to fix this is to check the stop variable inside the function setTimeout is executing.

var stop = 0;for (let i = 1; i <= 20; i++){  setTimeout(function(){    console.log(stop);    if (stop !== 1) {      $('ul').append('<li>'+ i +'</li>');    }  },i * 500);}
$('button').click(function(){ stop = 1;});
ul li{  list-style-type: none;  float: left;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul></ul>
<br><button>stop</button>

How to stop a for loop using Hotkey in JavaScript

You can't stop synchronous code with asynchronous code, because the async code isn't executed until you return to the main event loop.

If you want to run something repeatedly, use setInterval, then clear it when the event occurs.

var counter = 0;var interval;
function runMe() { if (counter == 1000) { clearInterval(interval); } else { counter++; $("#output").text(counter); }}
$(document).on("keydown", function(e) { if (e.key == 'm') { interval = setInterval(runMe, 10); } else if (e.key == 'a') { clearInterval(interval); }});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="output"></div>

Does return stop a loop?

Yes, functions always end whenever their control flow meets a return statement.

The following example demonstrates how return statements end a function’s execution.

function returnMe() {
for (var i = 0; i < 2; i++) {
if (i === 1) return i;
}
}

console.log(returnMe());

How can I exit for loop in Javascript?

Your logic is wrong...

Your for loop is setting the click event on all your answers, breaking it would just mean you wouldn't add the event on all the answers.

What you need to do is either :

  • remove the click event on all the answers AFTER the first click (in your clicked() function)
  • set a true/false "hasBeenClickedOn" flag that you'll check at the beginning of you clicked() function

For example :

<script>

var hasBeenClickedOn = false; // global flag

document.addEventListener("DOMContentLoaded", function() {
function clicked(answer, i) {

if (hasBeenClickedOn===true) { return false; } // check the flag
hasBeenClickedOn = true; // set the flag

if (answer[i].value == "correct")
{
answer[i].style.backgroundColor = "green";
let result = "<p>Correct!</p>";
document.getElementsByClassName("section")[0].insertAdjacentHTML('beforeend', result);
return;
}
else
{
answer[i].style.backgroundColor = "red";
let result = "<p>Wrong!</p>";
document.getElementsByClassName("section")[0].insertAdjacentHTML('beforeend', result);
return;
}
}
let answer = document.getElementsByTagName('button');
for (let i = 0; i < answer.length; i++) {
answer[i].addEventListener("click", () => {
{
clicked(answer, i);
}
});
}
});
</script>

How to stop looping once it found?

You can use array#some at this context,

var data = [
'one',
'two',
'three',
'four',
'three',
'five',
];

found = data.some(function(x) {
return x == "three";
});

console.log(found); // true or false

If you use filter, then the array will be filtered based on the truthy value returned inside of the callBack function. So if any matches found meaning, if the function returned with value true, then the element on that particular iteration will be collected in an array and finally the array will be returned.

Hence in your case ["three", "theree"] will be returned as a result. If you dont have any "three", then an empty array would be returned, At this context you have to make a additional check to find the truthy value as a result.

For Example:

var res = arr.filter(itm => someCondition);
var res = !!res.length;
console.log(res); //true or false.

So to avoid that over killing situation we are using Array#some.

Stopping my loop from running when a condition is met

The break will stop only the second for, meaning this one:

for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++)

The best option is to set a flag, initially false, and then set it to true besides making the loop break.
Then if the flag is set to true, break also the first for.

var flag = false;
for (mattCounter = 0; mattCounter < mattDeck.length; mattCounter++) {
for (jamesCounter = 0; jamesCounter < jamesDeck.length; jamesCounter++) {
if (mattDeck[mattCounter] === jamesDeck[jamesCounter]) {
console.log('SNAP!');
flag = true;
break;
} else {
console.log('Go again...');
}
}
if (flag) {
break;
}
};

Break for loop in JavaScript

In response to your statement, "My loop starts from 100, when it gets to 110, it breaks and skip a line. And continue reading when it reaches 120, skips a line:

        for(let i = 100; i <=300; i++){                         
if(i % 10 == 0) {
continue;
}
console.log(i);
}

A break will exit the loop completely, a continue will skip to the next iteration. This skips every loop iteration that's divisible by 10.

How to exit out of javascript forEach loop

According to the MDN web docs:

There is no way to stop or break a forEach() loop other than by
throwing an exception.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

How to make for each loop stop at first true condition

I would recommend using .some. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

This will return true if any of the user's match to your requirement else false

   let isUserMatched = allUsers.some(function(user) {
return user.userId === logId && user.userPassword === logPass)
});
if(isUserMatched){
// do something
}


Related Topics



Leave a reply



Submit