Throttle AJAX request for KeyUp and Paste events

So, I am calling an AJAX request for each keyup and paste event in jQuery in a text box:

  $("#server-label").bind("keyup paste", function() { $.ajax()... }); 

The problem is that there are too many AJAX requests if the user quickly presses the keys. What is the best way to wait until users stop typing for a few minutes (say 500ms) before calling an AJAX request. Basically, do not make an AJAX request until events with keys or inserts are triggered for 500 ms.

Thanks.

+4
source share
1 answer

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

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

You can also use a throttle or debounce , but I don’t think it would be necessary if you wrap your code inside an object or string function to go to setTimeout() function.

+11
source

Source: https://habr.com/ru/post/1410794/


All Articles