Pippo
Pippo

Reputation: 925

break from while loop from anonymous function

I am new to javascript, my background is python and ruby and I am having issues dealing with javascript anonymous functions, my problem is the following:

I have an element in the page which has an attribute value (true/false), I need to keep performing an action until this attribute changes value.

the code that I tried out is below, as you could guess, the break won't quit the loop if result.value == true... Any idea if I am in the right direction?

var counter = 0;
while (counter < 5) {
  this
    .click('#someelementid')
  counter++;
  this
    .getAttribute('#someelementid', 'disabled', function(result) {
      if (result.value == 'true') {
        this.break;
      }
    }.bind(this));
  this.api.pause(1000);
};

My assumption is that by binding this, I have access to the while block? Please correct me if I am wrong.

Upvotes: 0

Views: 679

Answers (2)

Subir Kumar Sao
Subir Kumar Sao

Reputation: 8401

The break inside a function would not break the loop outside the function.

Through getAttribute() get the result inline instead of having a callback. then you can break the function.

Or

Have a global variable. breakLoop = false; set it to true; inside the callback function. And put a check on this variable in the while loop. while(!breakLoop ..)

Another approach.

Don't have a loop altogether.

var counter = 0;

function doSomething(){
    this.click('#someelementid');
    counter++;

    this.getAttribute('#someelementid', 'disabled', function(result) {
        if(result.value != 'true' && counter<5){
            this.api.pause(1000);
            doSomething();
        }
    }.bind(this);

};

Upvotes: 0

anteAdamovic
anteAdamovic

Reputation: 1468

Have you tried changing your code to something like below ?

var counter = 0;
var arr = [1, 2, 3, 4, 5];
while (counter < 5) {
  arr.forEach(
    (element) => {
      if (counter < 5) { // if you don't have this it will print all 5, else it prints only 3
        console.log('Element value:', element);
      }
      if (element == 3) {
        counter = 5;
      }
    }
  );
}

What happens is this:

When you enter the while loop it will enter the forEach loop and start iterating, when it reaches element == 3 it will set counter to 5, but it still has to finish the current forEach loop, once it does it wont perform another while loop therefore exiting it.

So changing your code to:

var counter = 0;
while (counter < 5) {
  this
    .click('#someelementid')
  counter++;
  this
    .getAttribute('#someelementid', 'disabled', function(result) {
      if (result.value == 'true') {
        counter = 5; // This should do the trick (without 'this')
      }
    }.bind(this));
  this.api.pause(1000);
};

Upvotes: 2

Related Questions