The content of this article is about the implementation of function throttling and anti-shake in Javascript (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Function throttling (throttle): Continuously execute functions and execute functions at regular intervals
Mouse movement, mousemove event
DOM element dynamic positioning, window object resize and scroll events
etc...
function throttle(fn, delay) { var last; // 上次执行的时间 var timer; // 定时器 delay || (delay = 250); // 默认间隔为250ms return function() { var context = this; var args = arguments; var now = +new Date(); // 现在的时间 if (last && now < last + delay) { // 当前距离上次执行的时间小于设置的时间间隔 clearTimeout(timer); // 清除定时器 timer = setTimeout(function() { // delay时间后,执行函数 last = now; fn.apply(context, args); }, delay); } else { // 当前距离上次执行的时间大于等于设置的时间,直接执行函数 last = now; fn.apply(context, args); } }; }
Function debounce (debounce): The calling method will only be executed when the idle time must be greater than or equal to a certain value
Text input keydown event
Wait...
function debounce(fn, delay) { var timer; // 定时器 delay || (delay = 250); // 默认空闲时间250ms return function() { var context = this; var args = arguments; clearTimeout(timer); // 清除定时器 timer = setTimeout(function() { // delay时间后,执行函数 fn.apply(context, args); }, delay); }; }
The above is the detailed content of Implementation of function throttling and anti-shake in Javascript (with code). For more information, please follow other related articles on the PHP Chinese website!