5

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

1
  • either for reference, or so you dont reinvent the wheel, jqueryui's autocomplete plugin is excellent, and has this exact feature (it is of course optional, and when in use, you can set the delay)... Commented Jan 30, 2011 at 10:01

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

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!');
}

2 Comments

You are polluting the global scope with keyUpTime and keyUpTimeout
Key events won't trigger if you right-click and select Paste in the context menu.
2

There is another jquery plugin for this. It works fine for me a link

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.