Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 279
Sid Avatar asked Dec 01 '25 09:12

Sid


2 Answers

I have a similar feature in one of my windows applications. When the user types a character, a timer is started with a 1 second interval. In the Tick event, the search is started. If the user types again, the timer is restarted. So the search is only performed if the keyboard has been idle for more than a second.

Short sample (it's in C#, but easy enough to follow):

public partial class Form1 : Form
{
    private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

    public Form1()
    {
        InitializeComponent();

        timer.Interval = 1000;
        timer.Tick += new EventHandler(timer_Tick);
    }

    void timer_Tick(object sender, EventArgs e)
    {
        timer.Stop();

        // Do search, or what ever you want to do
        Console.WriteLine("Searching...");
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (timer.Enabled)
        {
            timer.Stop();
        }

        timer.Start();
    }
}

I'm not experienced in Javascript, but the anwswer from here will help you I think:

<input name="domain" type="text" id="domain" onKeyUp="javascript:chk_me();">

var timer;
    function chk_me(){

       clearTimeout(timer);
       timer=setTimeout(function validate(){...},1000);
    }
like image 109
Philip Wallace Avatar answered Dec 04 '25 00:12

Philip Wallace


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;
        }
    };
}
like image 40
Pickle Avatar answered Dec 04 '25 01:12

Pickle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!