防抖与节流
于2023-08-10 22:57:51发布
98
防抖
防抖指的是高频触发的事件,只获取最后一次
例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>防抖</title>
</head>
<body>
<input type="text">
<script>
const input = document.querySelector('input');
let id = undefined;
input.oninput = function() {
if (id) {
clearTimeout(id);
}
id = setTimeout(()=> {
console.log(this.value);
}, 500);
}
</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>防抖</title>
</head>
<body>
<input type="text">
<script>
// 防抖函数
function debounce(fn, dealy) {
let t = null;
return function () {
if (t) {
clearTimeout(t)
}
t = setTimeout(() => {
fn.call(this)
}, dealy);
}
}
const ipt = document.querySelector('input')
ipt.oninput = debounce(function () {
console.log(this.value)
}, 500)
</script>
</body>
</html>
节流
节流指的是高频触发的事件,尽量减少执行次数
例子
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>节流</title>
<style>
body {
height: 2000px;
}
</style>
</head>
<body>
<script>
// 第1步
// window.onscroll = function() {
// console.log(123);
// }
// 第2步,让滚动事件只执行一次
// let flag = true;
// window.onscroll = function() {
// if (flag) {
// console.log(123);
// flag = false;
// }
// }
// 第3步,减少滚动事件的执行次数
let flag = true;
window.onscroll = function() {
if (flag) {
console.log(123);
setTimeout(() => {
flag = true;
}, 1000);
}
flag = false;
}
</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>节流</title>
<style>
body {
height: 2000px;
}
</style>
</head>
<body>
<script>
function throttle(fn, delay) {
let flag = true
return function () {
if (flag) {
setTimeout(() => {
fn();
flag = true
}, delay);
}
flag = false
}
}
window.onscroll = throttle(function () {
console.log(123)
}, 500)
</script>
</body>
</html>