Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
How to call a setInterval function saved in a variable

I have a setInterval() function saved to a variable in order to able to clear it after with clearInterval().

  walkRight = setInterval(moveSnakeRight,1000) 
  walkLeft = setInterval(moveSnakeLeft, 1000)
  walkUp = setInterval(moveSnakeUp, 1000)
  walkDown = setInterval(moveSnakeDown, 1000) 

//and

      clearInterval(walkLeft)
      clearInterval(walkRight)
      clearInterval(walkUp)

My question is if there is any way to call the same SetInterval again , in this case , walkRight or walkLeft or walkUp. Any of them..

If I try walkRight() it won't work because it is not a function and if I try window.walkRight doesn't work either.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

The return value of setInterval is a number that identifies the interval solely for the purposes of clearing it.

There is no way to use that number to get any other information about the interval. You can't use it to determine what function was used to run the interval. You can't use it to call that function again.

If you want that information, you must store it separately.

For example:

const moveSnakeRight = () => {
  console.log('moving right');
};

class IntervalController {
  constructor(func) {
    this.func = func;
    this.start();
  }

  start() {
    if (typeof this.interval === "undefined") {
      this.interval = setInterval(this.func, 1000);
    }
  }

  stop() {
    clearInterval(this.interval);
    this.interval = undefined;
  }
}

const moveRightController = new IntervalController(moveSnakeRight);

document.querySelector('#start').addEventListener('click', () => moveRightController.start());

document.querySelector('#stop').addEventListener('click', () => moveRightController.stop());
<button id=start>Start</button>
<button id=stop>Stop</button>

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda