Throttle
Disregard for a certain period of time all the calls, suitable for the occurrence of relatively high frequency, the handling of heavier time to use.
Copy Code code as follows:
var throttle = function (func, threshold, Alt) {
var last = Date.now ();
Threshold = Threshold | | 100;
return function () {
var now = Date.now ();
if (Now-last < threshold) {
if (ALT) {
Alt.apply (this, arguments);
}
Return
}
last = Now;
Func.apply (this, arguments);
};
};
debounce
Executes the called method only when there is no call within a certain interval.
Copy Code code as follows:
var debounce = function (func, threshold, Execasap) {
var timeout = null;
Threshold = Threshold | | 100;
return function () {
var self = this;
var args = arguments;
var delayed = function () {
if (!EXECASAP) {
Func.apply (self, args);
}
timeout = null;
};
if (timeout) {
Cleartimeout (timeout);
else if (EXECASAP) {
Func.apply (self, args);
}
Timeout = settimeout (delayed, threshold);
};
};
Test
Copy Code code as follows:
var test = function (wrapper, threshold) {
var log = function () {
console.log (Date.now ()-start);
};
var wrapperedfunc = wrapper (log, threshold);
var start = Date.now ();
var arr = [];
for (var i = 0; i < i++) {
Arr.push (wrapperedfunc);
}
while (i > 0) {
var random = math.random () * 1000;
Console.log (' index: ' + i);
Console.log (' Random: ' + random);
SetTimeout (Arr[--i], random);
}
};
Test (debounce, 1000);
Test (throttle, 1000);