Javascript Throttle & Debounce Application Introduction _ Basics

Source: Internet
Author: User
Tags wrapper
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);
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.