Implementation of a simple JavaScript throttle

Throttle

javascriptThrottler is mainly used to delay the execution of certain actions, such as Ajax requests, if the input box registered the input event, then when the user input will continue to trigger this event, if the callback function continues to call the background interface through ajax, it will produce a certain serverPressure. Consider some way to defer Ajax requests, for example, by delaying 0.5s calls to the back-end interface when an input event is triggered, thus relieving the pressure on the server to some extent.
Here is a simple throttle.

 1 /**
 2 * Throttle 3 * @param [function] fn The function to be called after the event is triggered, that is, the function to throttling. 4 * @param [object]context fnThe execution context object has no execution object set to null. 5 * @param [number] delay Delay execution time millisecond 6 * @param param fnParameters needed 7 * @return nothing 8 */
 9 function throttle(fn, context, delay, param) {
10   clearTimeout(fn.timeoutId);
11 
12   fn.timeoutId = setTimeout(function () {
13     fn.call(context, param);
14   }, delay);
15 }

 

With parameter annotations and code, you should be able to get a general idea of what this throttle is going to do: defer the execution of fn, which is done through the setTimeout function.
### Use throttle
When used, it is also very simple to import FN, context, delay and params.

1 var ajaxFun = function() { // Slightly};
2 throttle(ajaxFun, null, 500, someParams);

In fact, the above throttle code can be simplified, but there is no robust above.

1 // Throttle
2 function throttle(fn, delay, param) {
3   setTimeout(function () {
4     fn(param);
5   }, delay);
6 }

This article was originally published on my own tortuous blog site: a simple JavaScript throttle implementation,The blog uses a source of open source, based on thinkjs and vuejs development, welcome you to stroll around.

Leave a Reply

Your email address will not be published. Required fields are marked *