“Debounce JS” Respostas de código

Debounce JS

function debounce(fn, delay) {
  let timer;
  return (() => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(), delay);
  })();
  
};

// usage
function someFn() {
  console.log('Hi')
};

debounce(someFn, 1000);
shahul

Debounce JS

const debounce = (fn, delay) => {
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(fn, delay);
  };
};

// Example
let count = 0;
const increaseCount = (num) => {
  count += num;
  console.log(count);
};

window.addEventListener('scroll', debounce(increaseCount.bind(null, 5), 200));
FADL

Debounce JS

function debounce(func, timeout = 300){
  let timer;
  return function(...args) {
    if (timer) {
      clearTimeout(timer);
    }
    
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  };
}
Inquisitive Iguana

Função de debounce em 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))
Muthukumar

Respostas semelhantes a “Debounce JS”

Perguntas semelhantes a “Debounce JS”

Mais respostas relacionadas para “Debounce JS” em JavaScript

Procure respostas de código populares por idioma

Procurar outros idiomas de código