Home > database >  How do I slow down a function or a for-loop in JavaScript?
How do I slow down a function or a for-loop in JavaScript?

Time:11-20

I'm new to programming so please go easy on me.

For my programming class we need to do a small game where a hero fights a dragon in different turns.

The hero as well as the dragon got 10 lifes. After every round (three turns) the hero or the dragon loses lifes.

The winner is chosen by rolling a dice. After every turn, I want to log "The hero won" or "The dragon won". Since it is a game, I would like to make the game more interesting by slowing down the console.

Now If I start the game, it is over in less than a second. Is there any possibility to slow it down?

function startQuest() {
    console.log("The Quest got started!");

   startGame();

}

function restartQuest() {
    console.log("Restart got clicked!");
}




// Klasse als Vorlage für Object:

class Fighter {

    constructor (name, lifeEnergy) {

        this.name = name;
        
        this.lifeEnergy = lifeEnergy;

    }

    getAttack() {

        let randomNumber = Math.floor(Math.random()*5)   2;  
        
        
        return randomNumber;
        
        };
        
        };

    


// __________________________

// Object erstellen mit Hilfe der Vorlage:

// ___________________________

let dragon = new Fighter("Dragon",10)
let hero = new Fighter("Hero",10)



// ___________________________

// Funktion zum Ermitteln des Gewinners des Zugs:

// ___________________________

function getTurnWinner(attackHero, attackDragon) {

    

    if (attackHero > attackDragon) {

        return -1;
    }
    
    else if (attackHero < attackDragon) {

        return 1;
    }

    else {
        
        return 0;
    }

};

// _______________________________

// Arrays zum Speichern der Punkte:

// ________________________________

let dragonPointsRoundEnd = [];
let heroPointsRoundEnd = [];

// ______________________________

// Funktion zur Vergabe der Punkte pro Zug:

// _______________________________

function getTurnPoints() {   


// ADD DELAY HERE?? 


let turnWinner = getTurnWinner(hero.getAttack(), dragon.getAttack());

if (turnWinner === -1) {

    console.log("The Hero won");
    heroPointsRoundEnd.push(3);
    dragonPointsRoundEnd.push(0);
}

else if (turnWinner === 1) {

    console.log("The Dragon won")
    heroPointsRoundEnd.push(0);
    dragonPointsRoundEnd.push(3);
}

else {

    console.log("Nobody won")
    heroPointsRoundEnd.push(1);
    dragonPointsRoundEnd.push(1);
}


};

// _____________________________

// Funktion speichert die Punkte pro Zug in die Arrays oben:

// _____________________________


function getRoundWinner() {

    for (let i = 0; i < 3; i  ) {

// ADD DELAY HERE??


        getTurnPoints();

}

};

// ____________________________

// In den folgenden Variablen werden die errechneten Gesamtpunkte der Runde gespeichert:

// ____________________________


let dragonCalculatedPoints = "";
let heroCalculatedPoints = "";

// ___________________________

// in dieser Funktion werden die Punkte errechnet welche in den Variablen oberhalb gespeichert werden:

// ___________________________

function calculateRoundPoints() {

getRoundWinner();

dragonCalculatedPoints = dragonPointsRoundEnd[0]   dragonPointsRoundEnd[1]   dragonPointsRoundEnd[2];

heroCalculatedPoints = heroPointsRoundEnd[0]   heroPointsRoundEnd[1]   heroPointsRoundEnd[2];

};

function calculateLifeRoundEnd() {

    calculateRoundPoints();

    if (dragonCalculatedPoints > heroCalculatedPoints && dragonCalculatedPoints >= 7) {
       console.log("The Dragon won the round");

       hero.lifeEnergy -= 3;
    }

    else if (dragonCalculatedPoints > heroCalculatedPoints) {
        console.log("The Dragon won the round");

        hero.lifeEnergy -= 1;
    }

    else if (heroCalculatedPoints > dragonCalculatedPoints && heroCalculatedPoints >= 7) {
        console.log("The Hero won the round")

        dragon.lifeEnergy -= 3;
    }

    else if (heroCalculatedPoints > dragonCalculatedPoints) {
        console.log("The Hero won the round")


        dragon.lifeEnergy -= 1;
    }

    else {
        console.log("Nobody won the round");
    }

};



// console.log(dragon.lifeEnergy);
// console.log(hero.lifeEnergy);


function startGame() {


while (dragon.lifeEnergy >= 1 && hero.lifeEnergy >= 1) {

    calculateLifeRoundEnd();

    dragonPointsRoundEnd = [];
    heroPointsRoundEnd = [];

    if (dragon.lifeEnergy <= 0) {

    console.log("The Hero won the battle with "   hero.lifeEnergy   " to 0");
    
    break;


    }

    else if (hero.lifeEnergy <= 0) {

        console.log("The Dragon won the battle with "   dragon.lifeEnergy   " to 0");

        break;
        
    }

    
};

};

I tried setTimeout(getTurnPoints,2000) but than the rounds didn't end anymore (Endless loop).

I also tried to slow down the loop in the getRoundWinner function with:

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

async function getRoundWinner() {

  for (let i = 0; i < 3; i  ) {
   
   await this.timeout(2000);
    getTurnPoints();
  }
  };

This didn't work either. (logs 'Nobody won').

What I want to get logged to the console:

The hero won! (2 seconds pause) The dragon won! (2 seconds pause) The hero won! (2 seconds pause) The hero won the round! .....

CodePudding user response:

Here is a working version of what you want . You have to use async await in the functions that use async code

function startQuest() {
  console.log("The Quest got started!");

 startGame();

}

function restartQuest() {
  console.log("Restart got clicked!");
}




// Klasse als Vorlage für Object:

class Fighter {

  constructor (name, lifeEnergy) {

      this.name = name;
      
      this.lifeEnergy = lifeEnergy;

  }

  getAttack() {

      let randomNumber = Math.floor(Math.random()*5)   2;  
      
      
      return randomNumber;
      
      };
      
      };

  


// __________________________

// Object erstellen mit Hilfe der Vorlage:

// ___________________________

let dragon = new Fighter("Dragon",10)
let hero = new Fighter("Hero",10)



// ___________________________

// Funktion zum Ermitteln des Gewinners des Zugs:

// ___________________________

function getTurnWinner(attackHero, attackDragon) {

  

  if (attackHero > attackDragon) {

      return -1;
  }
  
  else if (attackHero < attackDragon) {

      return 1;
  }

  else {
      
      return 0;
  }

};

// _______________________________

// Arrays zum Speichern der Punkte:

// ________________________________

let dragonPointsRoundEnd = [];
let heroPointsRoundEnd = [];

// ______________________________

// Funktion zur Vergabe der Punkte pro Zug:

// _______________________________

function getTurnPoints() {   


// ADD DELAY HERE?? 


let turnWinner = getTurnWinner(hero.getAttack(), dragon.getAttack());

if (turnWinner === -1) {

  console.log("The Hero won");
  heroPointsRoundEnd.push(3);
  dragonPointsRoundEnd.push(0);
}

else if (turnWinner === 1) {

  console.log("The Dragon won")
  heroPointsRoundEnd.push(0);
  dragonPointsRoundEnd.push(3);
}

else {

  console.log("Nobody won")
  heroPointsRoundEnd.push(1);
  dragonPointsRoundEnd.push(1);
}


};

// _____________________________

// Funktion speichert die Punkte pro Zug in die Arrays oben:

// _____________________________


async function getRoundWinner() {

  for (let i = 0; i < 3; i  ) {

// ADD DELAY HERE??
      await timeout(2000);

      getTurnPoints();

  }

};

// ____________________________

// In den folgenden Variablen werden die errechneten Gesamtpunkte der Runde gespeichert:

// ____________________________


let dragonCalculatedPoints = "";
let heroCalculatedPoints = "";

// ___________________________

// in dieser Funktion werden die Punkte errechnet welche in den Variablen oberhalb gespeichert werden:

// ___________________________

async function calculateRoundPoints() {

await getRoundWinner();

dragonCalculatedPoints = dragonPointsRoundEnd[0]   dragonPointsRoundEnd[1]   dragonPointsRoundEnd[2];

heroCalculatedPoints = heroPointsRoundEnd[0]   heroPointsRoundEnd[1]   heroPointsRoundEnd[2];

};

async function calculateLifeRoundEnd() {

  await calculateRoundPoints();

  if (dragonCalculatedPoints > heroCalculatedPoints && dragonCalculatedPoints >= 7) {
     console.log("The Dragon won the round");

     hero.lifeEnergy -= 3;
  }

  else if (dragonCalculatedPoints > heroCalculatedPoints) {
      console.log("The Dragon won the round");

      hero.lifeEnergy -= 1;
  }

  else if (heroCalculatedPoints > dragonCalculatedPoints && heroCalculatedPoints >= 7) {
      console.log("The Hero won the round")

      dragon.lifeEnergy -= 3;
  }

  else if (heroCalculatedPoints > dragonCalculatedPoints) {
      console.log("The Hero won the round")


      dragon.lifeEnergy -= 1;
  }

  else {
      console.log("Nobody won the round");
  }

};



// console.log(dragon.lifeEnergy);
// console.log(hero.lifeEnergy);


async function startGame() {


while (dragon.lifeEnergy >= 1 && hero.lifeEnergy >= 1) {

  await calculateLifeRoundEnd();

  dragonPointsRoundEnd = [];
  heroPointsRoundEnd = [];

  if (dragon.lifeEnergy <= 0) {

  console.log("The Hero won the battle with "   hero.lifeEnergy   " to 0");
  
  break;


  }

  else if (hero.lifeEnergy <= 0) {

      console.log("The Dragon won the battle with "   dragon.lifeEnergy   " to 0");

      break;
      
  }

  
};

};

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

startGame();
  • Related