jQuery UI Autocomplete Dynamic Delay

As part of a project I’ve been working on recently I chose to implement a jQuery UI autocomplete bar. Now, due to the application I have heavily customized it. One of these customizations is something that I call ‘dynamic delay’. So what is it? Basically the delay time varies depending on how many characters have been typed into the input box. As the user’s query becomes more specific, the delay dies off. So if you enter in “a”, it will wait a second until it returns any results. If you type in “as” it will have a 0.5s delay. I think it makes for a nicer user experience (than simply having a minimum character input). Also, from the ajax I only return the Top 25 rows, that way the load is never too high on the database. Click below for a demo, or read after the break to see how I do it. For best effect type “harry” slowly into the textbox in the demo … you’ll see the shortening delay.

Ok, so I start off with the HTML. I’m using Google’s Content Delivery Network to source my jQuery files (both styles and javascript). You could use a local copy if you wish.

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/south-street/jquery-ui.css" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<input type="text" id="searchBox" value="" />

That was simple. Now let’s make this an autocomplete. A full AJAX datasource is outside the scope of this how-to, so a simple list of items will suffice. In the head, add the following javascript:

<script language="javascript">
$(function () {    
    $('#searchBox').autocomplete({ source: ['harry', 'ron', 'hermione', 'voldemort'], delay: 1000 });
    $('#searchBox').keydown( function () {
        $('#searchBox').autocomplete('option', 'delay', 1000 / ($('#searchBox').val().length + 1));

What we’re doing here is doing the autocomplete as per usual with a delay of 1 second. Then we add a handler for the keydown method of the searchBox and when the key is pressed you divide the delay by the length of the input box.

Let me know what you think and if this makes for a nicer user experience. Try fudge around with the numbers too. Maybe even a different scaling algorithm? Feel free to use the code wherever you like!


  • sunel tr

    thanks a lot it helped me a lot ……………………

    one more request i need those value from the database (MYSQL) can u help me thanks in advance

  • Panagiotis

    works like a charm