- 节流和防抖在我们的日常代码中经常会遇到,下面我们来认识一下节流和防抖的应用场景以及它们的定义。
定义
- 相同点:两者的前提都是频繁触发
- 不同点:
- 节流:是确保函数特定的时间内至多执行一次。
- 防抖:是函数在特定的时间内不被再调用后执行。
应用场景
- 节流:鼠标连续多次click事件,mousemove 事件,监听滚动事件,比如是否滑到底部自动加载更多等等…
- 防抖:输入框搜索自动补全事件,频繁操作点赞和取消点赞等等
防抖
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="name">
<script>
let input = document.getElementById('name');
function debonce(func, context, delay){
return function(){
let args = [].slice.call(arguments);
//再次执行时清空定时器,确保只执行一次
func.id && clearTimeout( func.id );
func.id = setTimeout( function(){
func.apply(context,args);
},delay);
}
}
let debonceAjax = debonce(ajax, null, 2000);
input.addEventListener('keyup',function(e){
debonceAjax(e.target.value);
});
function ajax(data,type){
console.log('ajax request ' + data + ' success');
}
</script>
</body>
</html>
节流
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
li {
height: 50px;
margin: 20px;
background: #ccc;
}
</style>
</head>
<body>
<ul id="container"></ul>
<script>
let container = document.getElementById('container');
let lisHtml = '';
for(let i=0; i<30; i++){
lisHtml += `<li>我是第 ${i} 个数据</li>`
}
container.innerHTML = (lisHtml);
let throttleAjax = throttle(ajax, 1000);
document.addEventListener('scroll',function(){
throttleAjax('newData');
})
function throttle(fn, delay) {
let lastTime;
let timer;
delay || (delay = 300); // 默认间隔为300ms
return function() {
let context = this;
let args = arguments;
let nowTime = +new Date(); // 获取系统当前的时间
if (lastTime && nowTime < lastTime+ delay) { // 当前距离上次执行的时间小于设置的时间间隔
clearTimeout(timer); // 清除定时器
timer = setTimeout(function() { // delay时间后,执行函数
lastTime= nowTime ;
fn.apply(context, args);
}, delay);
} else { // 当前距离上次执行的时间大于等于设置的时间,直接执行函数
lastTime= nowTime ;
fn.apply(context, args);
}
};
}
function ajax(data){
console.log('这里是最新数据'+ data)
}
</script>
</body>
</html>
节流防抖优化函数