Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

84
Vistas
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"; 
    }
  }
   
}
5 months ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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 })
5 months ago · Santiago Trujillo Denunciar

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;
  ...
}
5 months ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.