How to make a counter with javascript speed setting to simulate game time

Asked

Viewed 45 times

2

I’m doing a football game simulation, and I need a function to count the time to 45;

What I did worked out, but it’s very fast, I wanted to be able to control the speed, for example, speed 1 counts slowly, speed 2 faster and so on.

I did it with loop:

var tempo = 0;

function TempoDeJogo() {
  while (tempo < 45) {
    tempo++;
    console.log(tempo);
  }
  console.log("Fim de Jogo");
}
TempoDeJogo();

Only the one I did, the count to 45 is practically instantaneous, I want to be able to adjust that speed.

2 answers

3


By toggling the @Augustovasques response, we could use recursion and adopt some parameter (number) for the function to set a delay time and thus control the execution speed.

Let’s assume the delays 3, 2 and 1 (fast, medium and slow), and we can use these values and define a time interval until the function TempoDeJogo be invoked in the recursion.

var tempo = 0;

function TempoDeJogo(atraso) {
  // verificação de segurança
  if (![1,2,3].includes(atraso)) atraso = 1 
  
  // divisão diminuir o atraso quanto maior for o valor de "atraso" (mais rápido)
  atrasoFinal = 1 / atraso

  const tempoAtrasoEmMs = atrasoFinal * 1_000 // tempo de atraso em ms

  if (tempo < 45) {
    tempo++;
    console.log(tempo);
    
    // chama a função TempoDeJogo novamente com o mesmo parâmetro
    return setTimeout(() => TempoDeJogo(atraso), tempoAtrasoEmMs) // delay para executar a recursão
  }
  console.log("Fim de Jogo");
}


TempoDeJogo(3) // executa rápido
// TempoDeJogo(2) // executa normalmente
// TempoDeJogo(1) // executa devagar

2

Use together setInterval() and clearInterval().

  • setInterval() creates a chronometer, returning an id to that chronometer, repeating the execution of a function continuously within a specified millisecond time interval.
  • clearInterval()cancels a timed and repetitive action that was previously established by a call to setInterval().

Just a few modifications to fit your code:

let tempo = 0;
let id = 0;

function TempoDeJogo() {
  //Ao invés de um loop faça uma verificação cada vez que função for chamada.
  if (tempo < 45) {
    tempo++;
    console.log(tempo);
    return;                      //Após a ação saia da função.
  }
  clearInterval(id);             //Finaliza o cronometro identificado por id.
  console.log("Fim de Jogo");
}

id = setInterval(TempoDeJogo, 1000);   //Inicializa o cronometro para chamar TempoDeJogo() a cada 1s.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.