1

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"; 
    }
  }
   
}
  • 3
    And what's your question about this? What have you tried to resolve your problem? – Nico Haase Aug 14 '22 at 12:12
  • 2
    [javascript call function only once](https://duckduckgo.com/?q=javascript+call+function+only+once+site%3Astackoverflow.com) – Andreas Aug 14 '22 at 12:15
  • 1
    See [*Function in JavaScript that can be called only once*](https://stackoverflow.com/questions/12713564/function-in-javascript-that-can-be-called-only-once). – RobG Aug 14 '22 at 12:15
  • 1
    Offtopic, but you don't need both `id` and `id2`, since when `backframe` fires, `frame` is not running. You can safely use only `id` variable – deaponn Aug 14 '22 at 12:19

2 Answers2

6

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 })
XMehdi01
  • 5,538
  • 2
  • 10
  • 34
Mina
  • 14,386
  • 3
  • 13
  • 26
1

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;
  ...
}
deaponn
  • 837
  • 2
  • 12