防抖:
只对最后一次操作发起请求
节流:
控制触发的请求次数
例子:
防抖措施:
<!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>
<input id="input" type="text">
<script>
let domElement = document.getElementById('input')
// 此时会产生数据抖动的情况,每当往input框里输入一个东西,都会打印一次value
// 会触发多次无用的请求
// domElement.oninput = function () {
// console.log(this.value);
// }
// 防抖:只对最后一次输入发起请求
// 封装 防抖函数 debounce
function debounce(fn, delay) {
let t = null
return function () {
if (t !== null) {
clearTimeout(t)
}
t = setTimeout(() => {
// console.log('setTimeout - this', this); // 指向 input 标签
fn.call(this)
}, delay)
}
}
domElement.oninput = debounce(function () {
// console.log('debounce - fn - this', this); // 指向 window 全局对象
console.log(this.value);
}, 666)
</script>
</body>
</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>
<div
id="div"
style="width:6666px;height:666px;background-color:aqua;">
</div>
<script>
// 滚动一次滚动条触发了多次时间,消耗性能
// window.onscroll = function () {
// console.log('滚动条滚动了')
// }
// 节流:控制触发次数
function throttle(fn, delay) {
let flag = true
return function () {
if (flag) {
setTimeout(() => {
fn.call(this)
flag = true
}, delay)
}
flag = false
}
}
window.onscroll = throttle(function () {
console.log('滚动条滚动了')
}, 666)
</script>
</body>
</html>