Ways to throttle ajax requests

早过忘川 提交于 2019-11-29 19:47:15

问题


I'm using the following code (written by another user) to throttle ajax requests in a livesearch function:

JSFiddle if you prefer a demo: http://jsfiddle.net/4xLVp/

It seems buggy, though. Clearing values with Ctrl+shift+back-arrow, and typing again causes a flurry of requests. Blank values also cause a request. It dones't seem right, especially compared to jQuery UI autocomplete, where request delays seem more measured.

    $('##tag-search').keyup(function() {
        var elem = $(this);
        if (elem.val().length >= 2) {
            elem.data('search',search).clearQueue().stop().delay(1000).queue(function() {
                $.ajax({ // ajax stuff
                    'success': function(data){ /*show result*/ }
                });
                if (elem.data('search') !=  string) return;
            });                                             
        } else if (string.length <= 1) { /*show original content*/ }
    });

Is there a better way to handle this?


回答1:


I would just use setTimeout:

(function() {
    var timeout;
    $('#tag-search').keyup( function() {
        var elem = $(this);
        if (elem.val().length >= 2) {
            clearTimeout(timeout);
            timeout = setTimeout(function() {
               $.ajax({ // ajax stuff
                    'success': function(data){ /*show result*/ }
                });     
            }, 80); // <-- choose some sensible value here                                      
        } else if (string.length <= 1) { /*show original content*/ }
    });
}());

There is also a debounce/throttle plugin.



来源:https://stackoverflow.com/questions/6967785/ways-to-throttle-ajax-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!