3

Jquery を使用して、このサイトのテキスト領域の下にあるタグの自動提案機能のような同様の機能を実装しようとしています。キーストロークごとではなく、数回のキーストローク後にリクエストがどのように送信されるかを理解しようとしています。アプリでリクエストをトリガーするために「keyup」イベントを使用しています。これにより、サーバーへのヒットが多すぎて、パフォーマンスに影響を与える可能性があることに気付きました。

すべてのキーアップでクエリを実行しないことで、stackOverflow が行うようなことをどのように実装できるかを説明できる人がいれば、それは素晴らしいことです。

4

3 に答える 3

6

Windows アプリケーションの 1 つに同様の機能があります。ユーザーが文字を入力すると、タイマーが 1 秒間隔で開始されます。Tick イベントでは、検索が開始されます。ユーザーが再度入力すると、タイマーが再開されます。そのため、検索は、キーボードが 1 秒以上アイドル状態になっている場合にのみ実行されます。

短いサンプル (C# で書かれていますが、理解するのは簡単です):

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();
    }
}

私はJavascriptの経験がありませんが、ここからの回答が役立つと思います:

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

var timer;
    function chk_me(){

       clearTimeout(timer);
       timer=setTimeout(function validate(){...},1000);
    }
于 2009-11-06T17:05:36.423 に答える
2
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;
        }
    };
}
于 2009-11-06T18:00:42.457 に答える
2

あなたが参照している方法は「デバウンス」と呼ばれます

通常、すべてのスクリプトの最後に「デバウンス」機能があります

var debounce=function(func, threshold, execAsap) {
    var timeout;
    return function debounced () {
        var obj = this, args = arguments;
        function delayed () {
            if (!execAsap)
                func.apply(obj, args);
            timeout = null; 
        };
        if (timeout)
            clearTimeout(timeout);
        else if (execAsap)
            func.apply(obj, args);
        timeout = setTimeout(delayed, threshold || 100); 
    }; 
};

そして、デバウンスの恩恵を受ける何かをするときはいつでも、それを一般的に使用できます

したがって、コードは次のように記述されます

$("#search_box").keyup(debounce(function() {
    //do stuff in this function  
}
,350 /*determines the delay in ms*/
,false /*should it execute on first keyup event, 
       or delay the first event until 
       the value in ms specified above*/
));

同様のユースケースについては、 Facebook Style AJAX Searchを参照してください...

于 2009-11-07T02:18:30.670 に答える