Jquery - Live ajax searches as user types, but with a slight delay?

Due to the environment, I would like to limit this to something small and concise rather than a plugin, if only it is an extension that can be inserted in the direction of other jquery code.

I have this code:

$("#txtSearch").live('keyup', function () { LoadList(1) }); 

I would like to add such a delay that if the user has to wait (as if stopping the input) 0.5 seconds before making the call.

So, if letters are typed with an interval less than X between successive keystrokes, ajax call does not occur.

Is there a tiny succinct way to do this with jQuery?

+8
jquery
source share
4 answers
 $("#txtSearch").live('keyup', function () { var value=$("#txtSearch").val(); setTimeout(function(){ if ($("#txtSearch").val() == value) { LoadList(1) } },500); }); 
+9
source share

Set a timeout and clear it each time you press a key before applying a new one:

 var timeout; $("body").on('keyup', '#txtSearch', function () { window.clearTimeout(timeout); timeout = window.setTimeout(function(){ LoadList(1); },500); }); 

example: http://jsfiddle.net/niklasvh/KgRjJ/

+20
source share

You can use the autocomplete widget in jQueryUI, which has a delay option:

A delay in milliseconds of Autofill waits after pressing a key to activate itself. A delay with a null value makes sense for local data (more responsive), but can provide more workload for remote data, although less responsive.

http://jqueryui.com/demos/autocomplete

+3
source share

It looks like this question was asked before:

How to delay the .keyup () handler until the user stops typing?

0
source share

All Articles