Successive AJAX Call on Key Stroke

In my project, I have a search box. Here I need to made a ajax call on key up so that it will return search results for each text. This is because I do not have any search button to made the ajax call. One more thing, I am using Filemaker database and on each ajax call a filemaker script is being called.

So if we type ‘MIL’, 3 ajax call will be made. And it takes more time to respond compared to directly posting the word ‘MIL’. I also aborted the existing ajax call before making another, but did not get any satisfactory result. Because on abort, it destroy the ajax call but can not stop the script that runs on filemaker server. So in this case, there are three scripts running simultaneously on filemaker server which makes the response slow.:(

Then I thought if we can make a single ajax call instead of three, the application will be fast. But the question is how to make a sinlge ajax call as in every key up the function is being called. There is a function setTimeout() which calls a function or evaluates an expression after a specified number of milliseconds.

Using this function(setTimeout()) I defined a delay function to made the ajax call with some delay. So that in each key up it will wait for a specific time before making the ajax call. In the mean time user will complete his typing and one ajax call will be made at the end.  In other words ajax call will be made if there is no action in the search box for a specific time.

So I have used following block of codes to get my work done:

//delay function
var delay = function(){
    var clock= 0;
    return function(callback, ms){
        clearTimeout (clock);
        clock= setTimeout(callback, ms);
    } 
}();
 
//ajax call
$("#id").keyup(function(){
    delay(function(){
        // ajax call
    }, 500);
});
150 150 Burnignorance | Where Minds Meet And Sparks Fly!