The throttle
Throttling simply means that only the first click is executed in a series of repeated clicks, and all subsequent clicks are invalidated until the first click is complete
function throttle(fn, delay) {
lettimer = null; // Use a closure to make the variable timer existreturn function () {
letcontext = this; // make the following apply point correctlylet args = arguments;
if(! timer) { timer = setTimeout(function() {// Use the arrow function to change this to fn. Apply (context, args); timer = null; }, delay); }}}Copy the code
Image stabilization
Anti-shake is the opposite of throttling. Anti-shake is performed only once in multiple clicks, and all previous clicks will be cancelled
function debounce(fn, delay) {
let timer = null;
return function () {
clearTimeout(timer);
let context = this;
let args = arguments;
timer = setTimeout(function() { fn.apply(context, args); }, delay); }}Copy the code
Where are anti – shake and throttling generally used
Image stabilization
When the user in a short period of time, many times click login, send SMS and other operations to request data when the text editor does not operate for a period of time, automatically save the search box for association, the user continuously input value, only pause for 1s before association
The throttle
The mouse mouseover event is executed only once when the browser scrolls, and the position information is calculated every 1s to avoid scrolling while calculating