Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay ajax call on key input in jQuery

Tags:

jquery

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

like image 886
Joel Avatar asked Jan 30 '11 09:01

Joel


People also ask

How to delay ajax call in jQuery?

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.

How do I delay Keyup?

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.

Does ajax have timeout?

The jQuery ajax timeout option is passed to the ajax() function with the value to specify the timeout for the request to the server.


2 Answers

Use the debounce plugin or the - better-documented - doTimeout plugin.

like image 181
ThiefMaster Avatar answered Oct 19 '22 15:10

ThiefMaster


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!');
}
like image 35
Marek Tuchalski Avatar answered Oct 19 '22 16:10

Marek Tuchalski