Created
September 21, 2021 18:20
-
-
Save juliozuppa/a5d3a593d60c1d71adec822b4bb13fc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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