Ways to throttle ajax requests

前端 未结 1 551
时光取名叫无心
时光取名叫无心 2021-01-02 16:51

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/

相关标签:
1条回答
  • 2021-01-02 17:21

    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.

    0 讨论(0)
提交回复
热议问题