Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

debounce function in javascript

// Add this in HTML
<button id="myid">Click Me</button>

// This is JS Code for debounce function
const debounce = (fn,delay ) => {
  let timeoutID; // Initially undefined
  
  return function(...args){
    
    // cancel previously unexecuted timeouts
    if(timeoutID){
      clearTimeout(timeoutID);
    }
    
    timeoutID = setTimeout( () => {
      fn(...args);
    }, delay)
  }
}


document.getElementById('myid').addEventListener('click', debounce(e => {
  console.log('you clicked me');
}, 2000))
Source by www.freecodecamp.org #
 
PREVIOUS NEXT
Tagged: #debounce #function #javascript
ADD COMMENT
Topic
Name
3+5 =