Trippze
Trippze

Reputation: 17

Ending a function before I recursively call it again

function startGame(diff){
 if (diff === 'easy'){
  loadEasy();
 }
}

function loadEasy(){
 difficultyPage.style.display = 'none';
 game.style.display = 'block';
 medHardTemplate.style.display = 'none';
 easyTemplate.style.display = 'block';

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

 colors = randomColorsArray(3);

 correctColor = colorToChoose(colors);
 colorRGB.innerHTML = correctColor;

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

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

  if(clickedColor === correctColor) {
    changeColorsOnWinEasy(correctColor);
    message.innerHTML = "Correct!"      
    again.textContent = "Play Again?"
    again.addEventListener('click', function(){
        again.textContent = "NEW COLORS";
        header.style.backgroundColor = "#232323";
        colorRGB.style.backgroundColor = "#232323";
        message.innerHTML = "";
        changeDifficulty('easy');
    });
}
else {
    this.style.backgroundColor = "#232323";
    message.innerHTML = "Wrong!"
 }
});
}
}

I don't know when to return the function so that I don't have many functions running at the same time if I spam the newGame button causing my app to lag. I added a return; at the end of the loadEasy function but that didn't seem to do anything.

Upvotes: 0

Views: 52

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138567

You may set a flag indicating the current gametype, then you dont need to rebind a button handler everytime, you just need to define the button as start the current game:

let gametype = "easy":

function startGame(diff){
  gametype = diff || gametype;
  if (gametype === 'easy'){
    loadEasy();
  }
  else {
    throw Error('unknown gametype: ' + gametype);
  }
}

function loadEasy(){
  //... Whatever  
}

newGame.addEventListener('onclick', function(){
  startGame();
});

So to start a game with the current gametype do:

startGame();

To start a different one, pass a parameter:

startGame("medium");

Upvotes: 1

Related Questions