防抖与节流的概念
防抖的概念
触发事件之后,在n秒内函数只执行一次。若在n秒内再次触发,则之前为未触发的取消,触发时间重新计算。
节流的概念
连续触发的事件,每间隔n秒执行一次;当然如果不触发了,不执行。
防抖与节流使用场景
- 输入框的连续输入
- 搜索框的连续输入
- 上拉刷新,下拉刷新的触发
- window的Resize
防抖代码实现
#防抖实现方式1: 第一次延迟执行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function( ){
const button = document.getElementById("button");
button.onclick = debounce( function(){
console.log("防抖后的有效函数执行了。。。");
}, 1000 );
}
//防抖函数(第一次立即执行)
function debounce( func123, wait ){
var timeout;
return function(){
if( timeout ){
//注意: clearTimeout函数运行后,timeout并不为null。
clearTimeout( timeout )
}
timeout = setTimeout( function(){
func123.apply(this);
timeout = null;
});
}
}
</script>
</head>
<body>
<button id="button">点击button</button>
</body>
</html>
#防抖实现方式2:第一次立即执行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
window.onload = function( ){
const button = document.getElementById("button");
button.onclick = debounce( function(){
console.log("防抖后的有效函数执行了。。。");
}, 1000 );
}
//防抖函数(第一次立即执行)
function debounceImmedicate( func123, wait ){
var timeout;
return function(){
if( timeout ){
//注意: clearTimeout函数运行后,timeout并不为null。
clearTimeout( timeout )
}
var callNow = !timeout;
//只有timeout为null,才会执行func123,如果不为null,就一直不会执行func123
timeout = setTimeout( function(){
timeout = null;
});
if( callNow ){
func123.apply(this);
}
}
}
</script>
</head>
<body>
<button id="button">点击button</button>
</body>
</html>
节流代码实现
- 实现 setTimeout() 方式实现
function throttle( func123, wait ){
let timeout;
return function(){
if( !timeout ){
timeout = setTimeout( ()=>{
func123.apply(this);
timeout = null;
}, 2000 );
}
}
}
content.onmouseomove = throttle( function){
console.log(“定时执行任务....”);
}, 2000 );
- 使用时间戳的方式实现
function throttle( func123, wait ){
var prev = 0;
return function(){
let now = Date.now();
if( now - prev > wait ){
func123.apply(this);
prev = now;
}
}
}
content.onmouseomove = throttle( function){
console.log(“定时执行任务....”);
}, 2000 );