Trippze
Trippze

Reputation: 17

How to end a function before it's called again

I have an addEventListener in my loadGame() and every time I hit the newGame button it launches loadGame(), but I have no return value in loadGame() so every time I hit the newGame button it relaunches the game, but the eventListeners of template[i] seem to overlap, so if I hit newGame 10 times, then hit the else statement of the loop, it'll run tryAgain() 10 times. How do I exit the function I'm on when hitting newGame? I tried adding a return statement at the end of loadGame() but that did nothing.

newGame.addEventListener('click', function(){
    changeDifficulty();
});

 function changeDifficulty(){       
            loadGame();         
    }

Loop in loadGame():

 for (var i = 0; i < template.length; i++) {
    //add colors to squares
    template[i].style.backgroundColor = colors[i];

    template[i].addEventListener('click', function(){
        var clickedColor = this.style.backgroundColor;

        if(clickedColor === correctColor) {
            clearInterval(timeout);
            message.innerHTML = "Correct!"; 
            newGame.textContent = "Play Again?";
        }
        else {
            fails++;
            tryAgain(difficulty);
            this.style.backgroundColor = "#232323";
            message.innerHTML = "Wrong!"
        }
   });

Upvotes: 0

Views: 64

Answers (1)

Cerbrus
Cerbrus

Reputation: 72857

You'll need to remove the event listeners before registering new ones:

function loadGame() {
    // <...>
    for (var i = 0; i < template.length; i++) {
        //add colors to squares
        template[i].style.backgroundColor = colors[i];

        template[i].addEventListener('click', clickHandler);
    }
    // <...>
}

function changeDifficulty() {
    // remove all event listeners
    for (var i = 0; i < template.length; i++) {
        template[i].removeEventListener('click', clickHandler);
    }     
    // Then call loadgame
    loadGame();         
}

function clickHandler(e) { // We need to be able to reference this function by name
    var clickedColor = e.target.style.backgroundColor;

    if(clickedColor === correctColor) {
        clearInterval(timeout);
        changeColorsOnWin(correctColor, template);
        message.innerHTML = "Correct!"; 
        newGame.textContent = "Play Again?";
    }
    else {
        fails++;
        tryAgain(difficulty);
        this.style.backgroundColor = "#232323";
        message.innerHTML = "Wrong!"
    }
}

Upvotes: 1

Related Questions