Home > Back-end >  Is there a way to stop a function from executing when a certain condition is true?
Is there a way to stop a function from executing when a certain condition is true?

Time:02-03

Here is the function. I want the function to stop running when the coditional statement is false. My conditional statement is suppose to return true when countryName == input.value but it never does and i want for a first time the function to stop running when the condtion is false

function generateRandomFlag() {
  return(
    fetch("https://restcountries.com/v3.1/all")
    .then((Response) => Response.json())
    .then((json) => {
      console.log(json);
      const random = Math.floor(Math.random() * 250);
      flag.innerHTML = `
    <img src='${json[random].flags.png}'/>
    `;
      const countryName = (message.innerHTML = json[random].name.common);
      console.log(countryName);
      if ( countryName == input.value) {
        console.log(true);
      } else {
        console.log(false);
        
      }
    })
  )
}
generateRandomFlag()

I dont even know what to write to stop a function from running when a certain condition is true or false

CodePudding user response:

this page has very good examples of what you looking for.

https://flexiple.com/javascript/javascript-exit-functions/

I created an example using Return to exit the function if names do not match

function  generateRandomFlag(){
var input = "usa";
 var countryName = "Canada";
 if (countryName != input) {
        console.log("will execute this line Hii");
       return;
        console.log("will not execute this line");
      } else {       
      console.log("Test");
      }
     }


generateRandomFlag()

CodePudding user response:

Here you can find a simple example of how to use While loop, you need to use a condition that the loop will keep doing the work until this condition ends or removed.

this example targeting if cond is true or not, so it will loop adding 1 to the count value until cond turned false

let cond = true
let count = 0

while(cond){
  console.log("condition is now :", cond)
  count  
  if(count == 3) cond = false
}

console.log("condition is now :", cond)

  • Related