Throttle AJAX Request On KeyUp and Paste Events

后端 未结 1 444
予麋鹿
予麋鹿 2020-12-16 07:35

So I am calling an AJAX request on every keyup and paste event in jQuery on a textbox:

 $(\"#server-label\").bind(\"keyup paste\",          


        
相关标签:
1条回答
  • 2020-12-16 08:14

    Try using setTimeout() and a timer var to keep track of it:

    var t;
    $("#server-label").on("keyup paste", function() {
        clearTimeout(t);
        t = setTimeout(function() {
            $.ajax({/*[...]*/});
            //...
        }, 500);
    });
    

    You can also use throttle or debounce but I don't think it'd be necessary if you wrap your code inside a function object or string to pass to the setTimeout() function.

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