The introduction
Events that fire too frequently in a short period of time (scrolling events, resize events, mousemove events, etc.) can easily cause the browser to freeze gameOver if handled improperly or left unchecked.
Take a chestnut
// Use your imagination to trigger dozens of times
let num = 1;
document.body.onmousemove = function () {
document.body.innerHTML = num ++ ;
}
Copy the code
Based on the above and similar scenarios, we need to make optimization, two solutions: anti-shake, throttling
Debounce
When the event is triggered, the function can only be executed once within n seconds. If the event is triggered again within N seconds, the function time is recalculated.
/ / image stabilization
function debounce(fn, delay) {
let timer;
return function (args) {
let that = this;
if (timer) clearTimeout(timer);
timer = setTimeout(() = >{ fn.call(that, args); }, delay); }}// When you swipe, you can see that the event will not output until you stop sliding for 1s.
let num = 1;
document.body.onmousemove = debounce(function () {
document.body.innerHTML = num ++ ;
}, 1000);
Copy the code
Throttle
By throttling, events are triggered at random, but only once in n seconds.
/ / throttling
function throttle(fn, delay) {
let flag = true;
return function (. args) {
let that = this;
if(! flag)return;
flag = false;
setTimeout(() = > {
fn.call(that, args);
flag = true; }, delay); }}// You can see the event output every 1s if you keep stroking
let num = 1;
document.body.onmousemove = throttle(function () {
document.body.innerHTML = num ++ ;
}, 1000)
Copy the code
thinking
If you want to know about closures, you should read the JS basics of the previous article