手写一个防抖与节流方法并测试
话不多说,直接上可以执行的代码:
<!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="box" style="height: 3000px"></div>
<script>
const dom = document.querySelector("#box");
console.log(dom);
// document.body.onscroll = () => {
// console.log(111);
// };
// window.addEventListener("scroll", () => {
// console.log(222);
// });
// 节流
document.body.onscroll = throttle((e) => {
console.log(111, e);
}, 500);
// 防抖
window.addEventListener(
"scroll",
debounce((e) => {
console.log(222, e);
}, 500)
);
// 防抖
function debounce(func, wait) {
let timer = null;
return function () {
const cxt = this;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.apply(cxt, Array.prototype.slice.call(arguments));
}, wait);
};
}
// 节流
function throttle(func, wait, immediate = false) {
let timer = null;
let once = immediate;
return function () {
const cxt = this;
if (once) {
// 节流之前是否立即执行一次
func.apply(cxt, Array.prototype.slice.call(arguments));
once = false;
}
if (!timer) {
timer = setTimeout(() => {
func.apply(cxt, Array.prototype.slice.call(arguments));
timer = null;
}, wait);
}
};
}
</script>
</body>
</html>
有疑问,可以评论区交流。有谬误还请指出