A, stabilization,
1-1 Basic concepts of anti-shake
The idea is that no matter how many callbacks are triggered, a function will execute only once in a given period of time. If we set a function to wait for 3 seconds, we will re-time the function for 3 seconds if we encounter a function call request within 3 seconds, until there is no function call request within 3 seconds, at which point we will execute the function, otherwise we will re-time the function and so on.
1-2 Principle of anti-shake
Stabilization principle is to use the timer, set a timer function is performed for the first time, and through the closure cached, called after discovery has set a timer is empty before the timer, and reset a new timer, if there is no empty timer, when the timer timing after the triggering function.
@param delay Specifies the number of milliseconds in which events are triggered. * @returns {Function} */
function debounce(fn,delay) {
let timer = null; // A timer is cached through a closure
return function () {
timer && clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(this.arguments); },delay); }}window.onscroll = debounce(function () {
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('Scroll bar position:' + scrollTop);
},200)
Copy the code
Second, the throttle
2-1 Throttling basic concept
Function throttling refers to the fact that a function is executed only once in an interval of 3 seconds, during which subsequent function call requests are ignored and the interval is not extended. Execution is triggered when a new function call is encountered for the first time after the 3-second interval, and subsequent function call requests are ignored for the next 3 seconds, and so on. Function throttling is ideal for scenarios where functions are frequently called, such as window.onresize() events, mousemove events, upload progress, etc.
2-2 Principle of throttling
The implementation principle is to use a Boolean variable to determine whether the callback can be performed. When the variable is true, a timer is generated, and the variable is reversed and stored in a closure. After the timer completes the callback, the variable is changed to true, and when the variable is false, the throttling function will not generate timer.
<input type="text" value="" id="input">
$('#input').on('keyup', throttle(function () {
console.log($(this).val());
// Ajax backend request....
}, 1000));
/** * Throttling function *@param Operation * triggered by fn event@param Delay How many milliseconds before an event is triggered *@returns {Function}* /
function throttle(fn, delay) {
let flag = true;
return function () {
if(! flag) {return;
}
flag = false;
setTimeout(() = > {
fn.apply(this.arguments);
flag = true; }, delay); }}Copy the code