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

249
Visualizações
How to only let the user call my function one

I am trying to move a box by letting the user click a button but I only want the user to be able to call the function once in 'javascript'.

function myMove() {
  let id = null; let id2 = null;
  const elem = document.getElementById("animate");   
  let pos = 0;
  clearInterval(id);
  id = setInterval(frame, 1);


  function frame() {
    if (pos == 250) {
      clearInterval(id);
       id2 = setInterval(backframe, 1);
    } else {
      pos++; 
      elem.style.top = pos + "px"; 
      elem.style.left = pos + "px"; 
    }
  }
  function backframe() {
    if (pos == 0) {
      clearInterval(id2);
      id = setInterval(frame, 1);
    } else {
      pos--; 
      elem.style.top = pos + "px"; 
      elem.style.left = pos + "px"; 
    }
  }
   
}
about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

To add an event listener, that just fires once, addEventListener can accept 3 arguments: type, listener, and options.

options is an object that has a property called once, you have set it to true.

Ex:

button.addEventListener('click', myMove, { once: true })
about 4 years ago · Santiago Trujillo Relatório

0

Apply these modification to your code:

let wasUsed = false;

function myMove() {
  if (wasUsed) return; // stops the function if it has ran before
  wasUsed = true;
  // the rest of your function doesn't change:
  let id = null; let id2 = null;
  ...
}
about 4 years ago · Santiago Trujillo 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