I think there are more improvements you should make than those suggested in the other answers.
- uses a debauchery or Throttle
- caches elements you need to use many times.
If you use a function mock the ajax waits a few milliseconds more before making each ajax request. Instead of making a request by keystroke, it waits for the last key and then makes the request. How we are making very small time intervals the user is not affected.
Caching for example $('#resultado')
makes you not need to go to the DOM too often to know what that element is.
Your code could then look like this:
(function() { // para não exportar variáveis para o escopo global
function debounce(fn, delay) { // defenição da função debounce
var timer = null;
return function() {
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function() {
fn.apply(context, args);
}, delay);
};
}
var resultado = document.getElementById('resultado'); // colocar o elemento em cache
var handler = debounce(function() { // criar uma função com debounce
var chars = this.value;
if (chars.length < 4) return; // parar aqui se o texto fôr muito curto
$.post('../Ajax/busca_nome', {
val: chars
}, function(busca) {
resultado.innerHTML = busca;
});
}, 400); // 400 ms de espera depois da ultima tecla
$('#nome').keyup(handler); // passar a super função ao jQuery
})();
Exactly that friend. Thank you very much.
– Eduardo Santos