I am building an auto-complete like script for text inputs. In order to avoid multiple unnecessary ajax calls, I would like to initiate ajax calls only after the user stopped typing text for 1 second. That way I will save some overhead calls for every key pressed. How can I achieve this using jQuery?
Thanks,
Joel
In responsive interface, the programmer needs to delay the ajax request to achieve some task before the response. This can be achieved by using jQuery setTimeout() function. This function executes the given Ajax code after some amount of given time.
In this article, we will see how to use keyup with a delay in jQuery. There are two ways to achieve the same: Approach 1: Using the keypress(), fadeIn(), delay() and fadeOut() methods in the jQuery library and clearTimeout() and setTimeout() methods in native JavaScript.
The jQuery ajax timeout option is passed to the ajax() function with the value to specify the timeout for the request to the server.
Use the debounce plugin or the - better-documented - doTimeout plugin.
You can try something like this. I wasn't playing with above yet. Just using plain js.
var keyUpTime = 1000; // 1 sec
var keyUpTimeout = null;
$('input[type=text]').keyup( function(e) {
clearTimeout(keyUpTimeout);
keyUpTimeout = setTimeout(function() { sendAjax(); }, keyUpTime);
});
function sendAjax() {
alert('Send it!');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With