js节流和防抖
一、防抖
- 目的是为了防止事件频繁触发,节省性能消耗
- 防抖主要应用于表单输入事件等容易频繁触发的事件中
- 防抖的主要特点是多次触发同一事件只有最后一次会生效
以表单input事件触发的请求案例为例子:
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>
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);
二、节流
- 目的是为了防止事件频繁触发,节省性能消耗
- 防抖主要应用于滚动事件等容易频繁触发的事件中
- 防抖的主要特点是多次触发同一事件只有第一会生效
以scroll事件触发的请求案例为例子:
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>
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);