防抖(debounce)实现方式
防抖的目的是:防止一个事件,被触发多次,频繁执行;(比如:按钮的点击去调取接口,会导致服务器被多次调取,影响性能);
防抖的结果:多次点击,只执行一次
防抖完整的方法
/*
* debounce:实现函数的防抖(目的是频繁触发中只执行一次)
* @params
* func:需要执行的函数
* wait:检测防抖的间隔频率
* immediate:是否是立即执行(如果为TRUE是控制第一次触发的时候就执行函数,默认FALSE是以最
后一次触发为准)
* @return
* 可被调用执行的函数
*/
function debounce(func, wait = 500, immediate = false) {
let timer = null;
return function anonymous(...params) {
let now = immediate && !timer;
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
// 执行函数:注意保持THIS和参数的完整度
!immediate ? func.call(this, ...params) : null;
}, wait);
now ? func.call(this, ...params) : null;
};
}
js中的实现方法
代码
<!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>Document</title>
</head>
<body>
<button id="btn" :disabled="" :loading="" open-type="" hover-class="button-hover" @click="btnClick">
按钮点击
</button>
<script>
var btn = document.getElementById('btn');
btn.addEventListener('click', debounce(btnClick, 1000, true))
function btnClick(e) {
console.log('点击方法,触发防抖', this, e)
}
function debounce(fn, wait = 500, immediate = false) {
// 首先定义个倒计时
let timer = null;
// 写个代理函数,去返回执行
return function anonymous(...params) {
// 点击后,立即去执行方法
if (immediate == true && !timer) {
// 外部函数的this不对,需要改变this
fn.call(this, ...params);
}
// 如果有timer就清除,只保留一个执行
if (timer) clearTimeout(timer);
// 返回的执行方法
timer = setTimeout(() => {
// 需要清空,不然下次点击进来不好使了
timer = null;
if (!immediate) {
fn.call(this, ...params);
}
}, wait);
}
}
</script>
</body>
</html>
后续继续更新,修改请不吝赐教,多多学习