如何避免keyup事件上连续ajax请求的开销?

Pra*_*sar 5 javascript optimization performance jquery

例如,当用户输入一些文本时,在搜索表单中,AJAX请求应该发送每个keyup事件,搜索键作为查询字符串.搜索键将是输入框中的值.

如果用户输入"ABCD",在这种情况下,前3个AJAX请求应该被杀/取消,因为在第4个AJAX请求中,searchkey将是"ABCD"

$(document).ready(function(){
    $("#searchInput").keyup(function(){
        ajaxSearch( $("#searchInput").val() );
    });
});
Run Code Online (Sandbox Code Playgroud)

在keyup事件中,我调用了"ajaxSearch()"函数.

function ajaxSearch(searchKey) {
    $.ajax({
        type: "get",
        url: "http://example.com/ajaxRequestHandler/",
        data: "action=search&searchkey=" + searchKey
    }).done(function() {
        /* process response */
    });
}
Run Code Online (Sandbox Code Playgroud)

小智 6

var request;
function ajaxSearch(searchKey) {
    /* if request is in-process, kill it */
    if(request) {
        request.abort();
    };

    request = $.ajax({
        type: "get",
        url: "http://example.com/ajaxRequestHandler/",
        data: "action=search&searchkey=" + searchKey
    }).done(function() {
        /* process response */

        /* response received, reset variable */
        request = null;
    });
}
Run Code Online (Sandbox Code Playgroud)


NJI*_*dar 5

避免多个ajax请求;我们可以参考并实现David Walsh 的博客文章中提到的去抖动功能它已经从去抖功能实现的一些伟大的见解Underscore.js。Debounce 函数每几分之一秒只会触发一次,而不是像触发一样快。它肯定有助于限制连续的网络请求。

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

var ajaxSearch = debounce(function(searchKey) {
 //send an AJAX network request.
    $.ajax({
        type: "get",
        url: "http://example.com/ajaxRequestHandler/",
        data: "action=search&searchkey=" + searchKey
    }).done(function() {
        /* process response */
    });
 //250 indicates the minimum time interval between the series of events being fired
}, 250);

$("#searchInput").keyup(function(){
    ajaxSearch($("#searchInput").val());
});
Run Code Online (Sandbox Code Playgroud)