防抖:频繁触发的函数,只让最后一次执行
引用场景,比如现在有一个input标签,然后我们想在里面搜索个东西,0.5秒后在控制台打印我们想要的东西,这个功能很简单,代码如下,首先我们得拿到这个input框,然后给它绑定一个oninput事件,这个事件是当在框里面输入东西时就会触发,如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text">
<script>
let inp = document.querySelector("input");
inp.oninput = function (){
console.log(this.value)
}
</script>
</body>
</html>
但是想下,我们作为前端开发人员,我们每次输入东西后,就会与后台进行数据的交互,而且每次就发一个请求,这很占用资源、耗性能。所以为了让请求次数没那么多的话,就用到了我们说的防抖。防抖:用户触发时间过于频繁,只要最后一次事件的操作。不想让它像刚刚那个,输入一次触发函数一次。想让它从输入后隔0.5秒或者1秒后才触发,时间我们自己定,输入后0.5秒内让它不触发,超过0.5秒后才触发,代码改下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text">
<script>
let inp = document.querySelector("input");
let t = null;
inp.oninput = function (){
if(t!==null){
clearTimeout(t)
}
t = setTimeout(() =>{
console.log(this.value)
},500)
}
</script>
</body>
</html>
效果如下:
优化代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text">
<script>
// 闭包:内部函数没有执行完成,外部函数变量不会被销毁
let inp = document.querySelector("input");
inp.oninput = debounce(function (){
console.log(this.value)
},500)
function debounce(fn,delay){
let t = null;
return function (){
if(t!==null){
clearTimeout(t)
}
t = setTimeout(() =>{
fn.call(this)
},delay)
}
}
</script>
</body>
</html>
/**
// 定义一个简单的防抖函数
const debounce = (func, wait) => {
let timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, arguments), wait);
};
};
// 定义一个需要防抖的函数
const myFunction = function() {
console.log('Function called');
};
// 使用防抖函数
const debouncedMyFunction = debounce(myFunction, 1000); // 1000毫秒后执行myFunction
// 在需要的时候调用debouncedMyFunction
window.addEventListener('resize', debouncedMyFunction);
**/
效果:
节流:控制执行次数。简单来说就是频繁触发的函数,一定时间内只触发一次
以下拉或者上拉滚动条为例:当滚动条频繁移动时,我们只让函数0.5秒左右才执行一次
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body style="height: 2000px">
<input type="text">
<script>
window.onscroll = throttle(function (){
console.log("你好====")
},500)
function throttle(fn,delay){
let flag = true;
return function (){
if(flag){
setTimeout(() =>{
fn.call(this)
flag = true;
},delay)
}
flag = false
}
}
</script>
</body>
</html>