JS防抖和节流模式的实际应用
防抖
首先我们先讲讲防抖,一个时间在n秒内触发了很多次,我们只执行一次,总之就是等事件触发完n秒不再触发,才执行
/**
* @desc 函数防抖
* @param func 函数
* @param wait 延迟执行毫秒数
*/
function debounce(func, wait) {
let timeout;
return function() {
let context = this; // this指向
let args = arguments;
if(timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context);
}, wait);
}
}
下面让我们开尝试调用一下
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="text" id="inputDom"/>
</body>
</html>
<script type="text/javascript">
var content = document.getElementById('inputDom');
function press() {
console.log("开始输入了");
}
content.debounce= function (){
throttle(press, 500);
}
</script>
可以看到,当连续输入内容,在500毫秒内只发一次,这就达到了防抖的效果了。
节流
持续触发某一事件,每隔n秒执行一次。关于节流的实现,有两种主流的实现方式,一种是使用时间戳,一种是设置定时器。
使用定时器
/** * @desc 函数节流 * @param func 函数 * @param wait 延迟执行的毫秒数 */ function throttle(func, wait) { let timeout; return function() { let context = this;
let args = argumetns;
if(!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait) } } }
使用时间戳
/**
* @desc 函数节流
* @param func 函数
* @param wait 延迟执行的毫秒数
*/
function throttle(func, wait) {
let previous = 0;
return function() {
let now = Date.now();
let context = this;
let args = arguments;
if(now - previous >wait) {
func.apply(context, args);
previous = now
}
}
}
浙公网安备 33010602011771号