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

Execute function when condition is met

i have a probably stupid question, but i cant figure it out.

In a piece of code below I have a global variable guestsTotal and event hadler where this variable is incremented by 1 by clicking button.

I’m trying to display in console some message when guestsTotal will be 12. But this doesn’t work.
My friend said that this wouldn’t work because event hadlers are asynchronous in JS. And my script was already executed.

So is there a way to do some actions when the value of guestsTotal will be 12?

let adultTotal = 0
let childTotal = 0
let babyTotal = 0
let guestsTotal = 0

adultButtonPlus.addEventListener('click', function (evt) {
    adultTotal++
    guestsTotal++
    adultCounter.textContent = adultTotal
    guestsInput.value = `${guestsTotal} guests`
})

if (guestsTotal === 12) {
    console.log('message')
}

>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 can do it two ways:

Check for the condition inside your event handler. This is very simple to do:

let adultTotal = 0
let childTotal = 0
let babyTotal = 0
let guestsTotal = 0
let adultButtonPlus = document.querySelector('#aButton');
adultButtonPlus.addEventListener('click', function (evt) {
    adultTotal++
    guestsTotal++
    //adultCounter.textContent = adultTotal
    //guestsInput.value = `${guestsTotal} guests`
if (guestsTotal === 12) {
    console.log('message')
}
});
<button id="aButton">Adult</button>

Or make use of getters and setters to listen to value changes in your guestsTotal count.

let adultTotal = 0
let childTotal = 0
let babyTotal = 0
const guestsTotal = {
  count: 0,
  get total() {
   return this.count;
  },
  set total(newCount) {
    this.count = newCount;
    if(this.count === 3){
      console.log('count is 3');
    }
    else if(this.count === 12){
      console.log('count is 12');
    }
  }
};


let adultButtonPlus = document.querySelector('#aButton');
adultButtonPlus.addEventListener('click', function (evt) {
    adultTotal++
    guestsTotal.total = guestsTotal.total+1;
    //adultCounter.textContent = adultTotal
    //guestsInput.value = `${guestsTotal} guests`
if (guestsTotal === 12) {
    console.log('message')
}
});
<button id="aButton">Adult</button>
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