Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

243
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!