Jquery Delay Between Keyup Functions

Frank picture Frank · Dec 3, 2010 · Viewed 10.8k times · Source

I have a bit of code that i am writing, trying to intergrate bing search API in my site with instant search results. I use jquery's keyup function to send the data to my server side script which then gets the bing search xml and shows the results.

The worry i have is that i will be making way too many unncessary hits to my scripts. Can someone please look at this and tell me how i can put a 1 second delay between keyups as a timer? so it will only update the reults every one seconds or so?

THis is what i have created so far, but i dont know if its correct???

<script type="text/javascript">
var delay = (function() {

    var timer = 0;

    return function(callback, ms) {

        clearTimeout(timer);

        timer = setTimeout(callback, ms);

    };

})();



function reloadsearch() {
    var searchterms = $('#q').val();
    if (searchterms.length >= 3) {
        delay(function() {
            var data = 'source=ajax&q=' + searchterms;
            $.ajax({
                type: "GET",
                url: "results/",
                data: data,
                success: function(html) {
                    if (html !== '') {
                        $("#search-results").html(html);
                        $("#search-results").fadeIn(500);
                    }
                }
            });
        }, 250);
    }

    else

    {
        $("#search-results").fadeOut(250);
    }
};



$('#q').keyup(function() {
    reloadsearch()
});

$(document).ready(function() {
    reloadsearch()
});

Answer

rcravens picture rcravens · Dec 3, 2010

Here is an example of an input box taking input and searching at a slower rate that typing.

http://jsbin.com/ebela4/8/edit

This example doesn't do the ajax piece, but you will get the idea. Try typing in the input box as fast as you can. It will update the search box at a delayed rate. It remembers that the state is 'dirty' and then refreshes if necessary.

Hope this gets you started.

Bob