Prevent addEventListener running another time in forEach loop

First of all I want to know if I am right about cause of the problem.

const updateScore = (isCorrect) => {
    // Update Game Variables
    if (isCorrect === true) {
      counter++
      score += 100;
    }
  }

  // Reset Styling
  const resetLoadedQuestionStyling = (isCorrect) => {
    questionScreen.style.display = 'none';
    answerArr.forEach(answer => {
      answer.classList.remove('correct');
      answer.classList.remove('wrong');
      answer.classList.remove('disable');
    });
    updateScore(isCorrect)
  }

  const styleAnswer = (div, isCorrect) => {
    if (isCorrect === true) {
      div.classList.add('correct');
    } else {
      div.classList.add('wrong');
      for (let i = 0; i < answerArr.length; i++) {
        if (i === currentQuestion.correct) {
          answerArr[i].classList.add('correct');
        }
      }
    }

    // Prevent Second Check
    answerArr.forEach(answer => {
      answer.classList.add('disable');
    });

    // Reset Styling
    setTimeout(() => {
      resetLoadedQuestionStyling(isCorrect);
    }, 3000);
  }

  const checkAnswer = (div, index) => {
    const userChoice = index;
    // Default Answer State
    let isCorrect = false;
    if (userChoice === currentQuestion.correct) {
      isCorrect = true;
    }
    styleAnswer(div, isCorrect);
  }

  answerArr.forEach((div, index) => {
    div.addEventListener('click', () => {
      checkAnswer(div, index);
    });
  });
  1. My counter updates 1,time, that 2 times… and I think the cause of this issue is that my EventListener is in a forEach loop, is that right?

  2. How to prevent it?

Thanks!

EDIT: Addded more of the code in order to get my idea better.

EDIT: answerArr is array of 4 divs in my HTML

56 thoughts on “Prevent addEventListener running another time in forEach loop”

Leave a Comment