Is it possible to leave the delay argument of the dynamic setInterval?

Asked

Viewed 133 times

1

It is possible to pass the millisecond parameter in the function setInteval as a variable so that it can be changed dynamically or necessarily needs to be a static number?

I did some tests but did not succeed and I did not find any concrete information in a brief research I did...

The idea of example would be in a game, conditioning the score the higher the faster the function performs increasing the difficulty.

let mostrarBaloes = setInterval(criarBaloes, tempo);

Time starts with 1000, but when the score reach 100, time becomes 900, score 200 time 800, etc.

Is it possible or am I mistaken in something?

3 answers

3

The interval is scheduled so that every X seconds the function passed will be executed as callback. Therefore, for each interval you create, the time between each "run" will be constant and cannot be changed.

To simulate this change, you must remove the already existing interval and create a new one, with the updated time. For this, you can use the function clearInterval, passing as argument the interval ID (returned by setInterval).

const incrBtn = document.querySelector('#incr');
const decrBtn = document.querySelector('#decr');

// Função que será executada pelo `setInterval`:
function intervalCallback() {
  console.log(new Date().toLocaleTimeString('pt-BR'));
}

// Número que usaremos para o "incremento" ou "decremento".
const step = 250;

// Intervalo (inicialmente 1s).
let currentIntervalTimeout = 1000;
// Armazenaremos o ID do intervalo em execução aqui.
let currentIntervalId = null;

// Função para criar (ou recriar) o intervalo:
function runInterval() {
  if (currentIntervalId) {
    clearInterval(currentIntervalId);
  }

  console.log('Intervalo atual (em ms):', currentIntervalTimeout);
  currentIntervalId = setInterval(intervalCallback, currentIntervalTimeout);
}

// Inicia o intervalo pela primeira vez:
window.addEventListener('load', () => {
  runInterval();
});

// Incrementar o intervalo:
incrBtn.addEventListener('click', () => {
  currentIntervalTimeout += step;
  runInterval();
});

// Decrementar o intervalo:
decrBtn.addEventListener('click', () => {
  currentIntervalTimeout -= step;
  runInterval();
});
<button id="incr">Incrementar</button>
<button id="decr">Decrementar</button>

Another alternative, a little simpler, is to use setTimeoutrecursive s, as demonstrated by this other answer.

2

Probably you can achieve using setTimeout.

var tempo = 1000;
function x() {
  tempo = Math.random()*1000; // altera o tempo aqui
  setTimeout(x,tempo);
  console.log("executou")
}
let mostrarBaloes = setTimeout(x, tempo);

I used a random number to illustrate time change.

1

Depending on your logic you may prefer to use the method setTimeout in place of setInterval. The difference to this method is that callback (Once) is executed after the given time.

So at the end of your method criarBaloes you can call again the same method with the setTimeout, creating a "dynamic" interval between the execution of this method.

Browser other questions tagged

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