Skip to content

Instantly share code, notes, and snippets.

@juliozuppa
Created September 21, 2021 18:20
Show Gist options
  • Save juliozuppa/a5d3a593d60c1d71adec822b4bb13fc3 to your computer and use it in GitHub Desktop.
Save juliozuppa/a5d3a593d60c1d71adec822b4bb13fc3 to your computer and use it in GitHub Desktop.
/**
* Função que aguarda um tempo antes de executar uma requisição ou ação
* evitando realizar multiplas vezes em um evento, um autocomplete por exemplo
*
* @param fn
* @param delay
* @returns {function(): void}
*/
const debounce = function (fn, delay) {
let timer = null;
return function () {
let context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
// example calling draw datatable method (sending ajax request)
// fire again only after type three letters (value.length > 2)
// and after 1 second
$(elem).on('keyup', debounce(function (event) {
event.preventDefault();
let value = $(this).val().trim().replace(/[%]+/, ' ').replace(/[ ]{2,}/, ' ');
if (value.length > 2 || value.length === 0) {
dataTable.draw();
}
}, 1000));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment