Front-end performance optimization - image stabilization and the throttle
What is image stabilization and throttle
- Image stabilization
so that function for some time after the trigger event and then stop execution - Throttling
let function at a fixed frequency trigger
Why shake throttle
When we give a button or move the mouse to add the corresponding event time, if not require real-time response, you can use image stabilization, throttling to optimize the performance of the page
html
<button id="add">点击加一</button>
<label id="addLable" for="add"></label>
js
let count = 0;
const add = document.querySelector('#add');
const addLabel = document.querySelector('#addLable');
add.addEventListener('click', () => {
addLable.innerHTML = ++count;
});
Shake
The principle is to let anti-shake function allows the function to delay execution, if triggered during a new event, cancel the original plan delayed
html
<button id="add1">防抖加一</button>
<label id="addLable1" for="add1"></label>
js
let count1 = 0;
const add1 = document.querySelector('#add1');
const addLabel1 = document.querySelector('#addLable1');
let timeout;
const add1Click = function() {
addLabel1.innerHTML = ++count1;
};
add1.addEventListener('click', () => {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(add1Click, 500);
});
More elegant code
to know the rationale behind, you can help us achieve it with lodash tool library, looking more convenient and simple
_.debounce (FUNC, timeout)
lodash official website
let count1 = 0;
const add1 = document.querySelector('#add1');
const addLabel1 = document.querySelector('#addLable1');
let timeout;
const add1Click = function() {
addLabel1.innerHTML = ++count1;
};
// add1.addEventListener('click', () => {
// if (timeout) {
// clearTimeout(timeout);
// }
// timeout = setTimeout(add2Click, 500);
// });
add1.addEventListener('click', _.debounce(add1Click, 500));
Throttling
Throttle function within a certain time, only trigger once
html
<button id="add2">节流加一</button>
<label id="addLable2" for="add2"></label>
js
let count2 = 0;
const add2 = document.querySelector('#add2');
const addLabel2 = document.querySelector('#addLable2');
const add2Click = function() {
addLabel2.innerHTML = ++count2;
};
let beAbleClick = true;
add2.addEventListener('click', () => {
if (!beAbleClick) {
return;
}
setTimeout(() => {
add2Click();
beAbleClick = true;
}, 500);
beAbleClick = false;
});
More elegantly
same lodash tools have methods available _.throttle (func, timeout)
let count2 = 0;
const add2 = document.querySelector('#add2');
const addLabel2 = document.querySelector('#addLable2');
const add2Click = function() {
addLabel2.innerHTML = ++count2;
};
// let beAbleClick = true;
// add2.addEventListener('click', () => {
// if (!beAbleClick) {
// return;
// }
// setTimeout(() => {
// add2Click();
// beAbleClick = true;
// }, 500);
// beAbleClick = false;
// });
add2.addEventListener('click', _.throttle(add2Click, 500));
``