Gumu Tianqi Tag: JavaScript, performance, JS performance, callback function, latency Function
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.
These event listening functions are 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, using mprocessing: function () {// Code }, process: function () {cleartimeout (this. timeoutid); this. timeoutid = setTimeout (function () {processor. optional mprocessing () ;}, 100) ;}; // call processor. process ();
Performprocessing is the function to be called, andProgramThe entry is in process. Every time you enter process, the worker mprocessing function to be called 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 performprocessing is executed at least once every 100 milliseconds. The principle is very simple. The following function also uses this principle, the closure achieves the same purpose. 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 );};}
In addition, someone wrote plug-ins with the same functions for jquery: Click here to transfer them to jquery plugins
Google closure Library also has similar APIs: Click here to transfer to Google Code