The main idea of function throttling technology is to block repeated function calls through a timer. For functions we use internally, this technology is generally of little significance and is not recommended. It may lose processing of some data. However, it makes sense for functions called on the user interface. For example, a listening function for a mousemove or resize event in IE.
This type of event listening function is often accompanied by two main features: 1. Repeated triggering in a short period of time; 2. A large number of DOM operations. As we all know, DOM operations have a high overhead on memory and CPU, especially when both feature 1 is met, it often puts a lot of pressure on browsers. The function throttling technology is used to reduce the frequency of function calls and improve the performance.
The general mode of this technique is as follows:
- Var processor = {
- TimeoutId: null,
-
- PerformProcessing: function (){
- // Code to be executed
- },
-
- Process: function (){
- ClearTimeout (this. timeoutId );
- This. timeoutId = setTimeout (function (){
- Processor. Merge mprocessing ();
- },100 );
- }
- };
-
- // Call
- Processor. process ();
- PerformProcessing is the function to be called, and the program entry is in process. Every time you enter process, the function that you actually want to call
- PerformProcessing will be executed with a latency of 100 milliseconds. If process is called again during this period, the previous timer will be reset,
- Re-start timing. This ensures that the code in the receivmprocessing can be executed at least once every 100 milliseconds. The principle is very simple,
- The following function uses this principle and achieves the same purpose through the closure. It accepts two parameters. The first is the function to be actually executed, and the second is the interval.
- Function throttle (fn, delay ){
- Var timer = null;
- Return function (){
- Var context = this, args = arguments;
- ClearTimeout (timer );
- Timer = setTimeout (function (){
- Fn. apply (context, args );
- }, Delay );
- };
- }