Javascript - Prevent Function From Executing Multiple Times
I have a function which is executed on a click (or taphold) because I am working with Cordova.  The problem is that a function calls on the next object from Parse.com which shows i
Solution 1:
You are experiencing "bounce", a problem caused by one impact registering multiple times in short succession. To get around it, you need to put a very short timeout on your function. (20ms or so) You can either use a third-party library such as LoDash which has many useful utility functions such as _.debounce which performs this, or you can do it yourself like this:
var lastClick = 0;
var delay = 20;
function doClick() {
  if (lastClick >= (Date.now() - delay))
    return;
  lastClick = Date.now();
  // do things
  alert("Hello!");
}<button onclick="doClick()">Push me</button>Solution 2:
This is a similar code that I use regularly.
const delay = 500; // anti-rebound for 500ms
let lastExecution = 0;
function myFunction(){
    if ((lastExecution + delay) < Date.now()){
       // execute my lines
       lastExecution = Date.now() 
    }
}
Post a Comment for "Javascript - Prevent Function From Executing Multiple Times"