Home > Mobile >  If repeated triggering of click events is prohibited through javascript, resulting in repeated API r
If repeated triggering of click events is prohibited through javascript, resulting in repeated API r

Time:01-14

I am a front-end novice. There is a need for users to click the button to get points. When the button is clicked, an API will be triggered, but I am worried that the user will repeatedly send API requests to the backend if the user clicks too fast. At present, my knowledge only knows that it can be written as in the example. I would like to ask if there is a better or safer way? thanks

let btn = document.querySelector("#btn");

btn.addEventListener('click', function(e) {
  console.log("Receive point")
  btn.setAttribute('disabled', true)
})
<button id="btn">Receive points</button>

CodePudding user response:

You can remove event listener using removeEventListener after first click instead of disable button attribute.

Example:

window.addEventListener("load", () => {
  document.getElementById("btn").addEventListener("click", removeclick);
});


function removeclick() {
  console.log("Clicked 1 time . No new event fired.");
  document.getElementById("btn").removeEventListener("click", removeclick);
}
<button id="btn">Receive points</button>

Or use third parameter once:true of addEventListener, which allow the event listener to run only once.

Example:

var element = document.getElementById("btn");
element.addEventListener('click', function(e) {
  console.log("Clicked 1 time . No new event fired.");
}, {
  once: true
});
<button id="btn">Receive points</button>

CodePudding user response:

You can do it in JavaScript, maybe user something know about HTML and he/she can remove disabled attribute easily. so, you should do it in JavaScript like this:

let btn = document.querySelector("#btn");
let disabled_btn = false;

btn.addEventListener('click', function(e) {
  if(!disabled_btn){
      disabled_btn = true;
      btn.setAttribute('disabled', true);
      console.log("Receiving point ...")
      
      setTimeout(() => {
         console.log("Received");
         btn.removeAttribute('disabled');
         disabled_btn = false; // after receive data from server
      },2000);
  }
})
<button id="btn">click me!</button>

  • Related