js throttling and anti-shake
1. Anti-shake
- The purpose is to prevent events from being triggered frequently and save performance consumption.
- Anti-shake is mainly used in events that are easily triggered frequently such as form input events.
- The main feature of anti-shake is that only the last time the same event is triggered multiple times will take effect.
Take the request case triggered by the form input event as an example:
code in html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2022-8-23</title>
</head>
<body>
<input type="text" id="debouce">
<script src="../2022-8-23.js"></script>
</body>
</html>
code in js
let request = function(value) {
console.log('请求的数据:', value);
};
// 防抖
const debounce = function(fn, delay = 500) {
let timer = null;
let content = this;
return function(...ags) {
if(timer) {
clearTimeout(timer);
timer = null;
} else {
fn.apply(content, ags);
};
timer = setTimeout(() => {
fn.apply(content, ags);
}, delay);
}
}
const inputFn = function (e) {
let value = e.target.value;
request(value);
}
document.querySelector("#debouce").oninput = debounce(inputFn, 1000);
2. Throttling
- The purpose is to prevent events from being triggered frequently and save performance consumption.
- Anti-shake is mainly used in events that are easily triggered frequently such as scrolling events.
- The main feature of anti-shake is that only the first time the same event is triggered multiple times will take effect.
Take the request case triggered by the scroll event as an example:
code in html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="width: 100%;height: 4000px;background: rgba(49, 135, 9, 0.563);">
<script src="../2022-8-26.js"></script>
</body>
</html>
code in js
// 节流
// 核心思想:
// 1、在一定的时间范围内执行一次函数
// 2、部分逻辑和防抖一致
let scrollEvevtCount = 0;
let scrollFn = function() {
scrollEvevtCount++;
console.log('scroll事件触发:', scrollEvevtCount)
};
let throttle = function(fn, delay) {
let timer = null;
let pre = new Date().getTime();
return function(...ags) {
let now = new Date().getTime();
if (now - pre > delay) {
timer = setTimeout(function() {
fn.apply(this, ags);
pre = now;
clearTimeout(timer);
}, delay);
}
}
}
let throttle2 = function(fn, delay) {
let content = this;
let timer = null;
let lock = false;
return function () {
if (!lock) {
lock = true;
timer = setTimeout(function() {
fn.apply(content, arguments);
clearTimeout(timer);
lock = false;
}, delay);
}
}
}
document.body.onscroll = throttle(scrollFn, 500);