Home > Mobile >  How to only let the user call my function one
How to only let the user call my function one

Time:08-14

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"; 
    }
  }
   
}

CodePudding user response:

To add an event listener, that just fire once, addEventListener can accpet 3 parameters, type, listener, options

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

Ex:

button.addEventListener('click', myMove, { once: true })

CodePudding user response:

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;
  ...
}
  • Related