Search code examples
jqueryautocompleteautosuggest

How does the AutoSuggest feature for tags in StackOverflow avoid querying on every key stroke


I am trying to implement a similar feature like the autosuggest feature for tags available below the text area on this site using Jquery. I am trying to figure out how the requests are sent after a few keystrokes and not after every keystroke. I am using a 'keyup' event to trigger the request on my app. I was made to realize that this may result in too many server hits and may affect performance.

It would be awesome if some could explain how i could implement the kind of thing stackOverflow does by not having a query run on every keyup.


Solution

  • var activity = new ActivityTimer(1000, function() {
        doSearch();
    });
    
    $("#searchBox").keyup(function(){ activity.reset() });
    
    function ActivityTimer(deadline, callback) {
        var timer = -1;
    
        this.reset = function() {
            this.cancel();
            timer = setTimeout(callback, deadline);
        };
    
        this.cancel = function() {
            if(timer >= 0) {
                clearTimeout(timer);
                timer = -1;
            }
        };
    }