Search code examples
javascriptscoping

How to update a variable to use in another scope


I have a variable let second = 20 that i make 1 lower until it hits 0. When it hits 0 i want to stop running a part of my code but the variable second is always 20 when i use it because i make it lower in another scope. Sorry if my explenation is a bit unclear.

Here is the code:

votingEnd = document.querySelector(".imposters__voting");
imposters = document.querySelectorAll(".imposter");
let second = 20;

window.addEventListener("load", function () {
  let myinterval;

  myinterval = setInterval(function () {
    second--;

    if (second < 11) {
      votingEnd.style.color = "red";
    }

    votingEnd.innerHTML = `Voting ends in: ${second}s`;
    if (second == 0) {
      clearInterval(myinterval);
      votingEnd.innerHTML = `Voting has ended`;
    }
  }, 1000);
});

if (second > 0) {
  //second is still 20 here because i lowered it in my function above. How can i solve this
  for (let i = 0; i < imposters.length; i++) {
    imposters[i].addEventListener("click", function () {
      let count = 0;
      while (count < imposters.length) {
        imposters[count++].classList.remove("voted");
      }
      this.classList.add("voted");
    });
  }
}

Solution

  • You could put the if (second > 0) inside the click function that way it will check for the most recent value of second instead of just once on load like so

    for(let i = 0; i < imposters.length; i++){
        imposters[i].addEventListener("click", function () {
            if (second > 0) {
            let count = 0;
                while (count < imposters.length) {
                    imposters[count++].classList.remove("voted");
                        }
                this.classList.add("voted");
            }
        });