Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit the loop abruptly

Let's imagine the following code:

function DoSomethingHard(parameter1, parameter2, parameter3){
  // Do Something Hard Here
}

var i;
for(i = 0; i <= stuff.length; i++) {
  // "stuff" is an array
  DoSomethingHard(stuff[i].something1, stuff[i].something2, stuff[i].something3);
}

$( "#button_to_cancel" ).click(function() {
  //something to cancel
});
  • Suppose the array "stuff" has 100 positions, so the for loop will run 100 times, ie, it will do "Do Something Hard" 100 times.
  • Let's also consider that "DoSomethingHard" takes about 5 seconds to run completely.

My question is: How do I manage the cancellation of "DoSomethingHard"? For example, if it has already run 50 times, how can I cancel the subsequent executions through a button? I did not succeed in my attempts and it always ends up running the whole loop ....

Thanks in advance :)

like image 724
Pedro Antônio Avatar asked Mar 17 '26 05:03

Pedro Antônio


1 Answers

Javascript is single threaded, and a for loop executes until it is finished. I would do something like this to allow time for the cancel.

function DoSomethingHard(param){
 //do something
}

var i = 0;
var loopInterval = setInterval(function() {
  if (i >= stuff.length) {
    clearInterval(loopInterval);
    return;
  }
  DoSomethingHard(stuff[i]);
  i++
}, 10);

$( "#button_to_cancel" ).click(function() {
  clearInterval(loopInterval);
});
like image 194
Jason P Avatar answered Mar 19 '26 19:03

Jason P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!