如何在再次调用函数之前结束函数

时间:2017-08-30 07:06:46

标签: javascript algorithm loops javascript-events

我的loadGame()中有一个addEventListener,每次点击newGame按钮都会启动loadGame(),但是我在loadGame()中没有返回值,所以每次点击newGame按钮都会重新启动游戏,但是template [i]的eventListeners似乎重叠,所以如果我点击newGame 10次,然后点击循环的else语句,它将运行tryAgain()10次。如何在击中newGame时退出我正在使用的功能?我尝试在loadGame()的末尾添加一个return语句,但没有做任何事情。

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

 function changeDifficulty(){       
            loadGame();         
    }

在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!"
        }
   });

1 个答案:

答案 0 :(得分:1)

您需要在注册新事件之前删除事件侦听器:

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!"
    }
}