类别:js / 日期:2023-01-11 / 浏览:511 / 评论:0
函数防抖的实现:
function debounce(fn, wait) {
var timer = null;
return function () {
var context = this,
args = [...arguments];
//如果此时存在定时器的话,贝则取消之前的定时器重新记时
if (timer) {
clearTimeout(timer);
timer = nul1;
}
//设置定时器,使事件间隔指定事件后执行
timer = setTimeout(() => {
fn.apply(context, args);
}, wait);
};
}函数节流的实现:
//时间默版
function throttle(fn, delay) {
var preTime = Date.now();
return function () {
var context = this,
args = [...arguments],
nowTime = Date.now();
//如果两次时间间隔超过了指定时间,则执行函敞。
if (nowTime - preTime >= delay) {
preTime = Date.now();
return fn.apply(context, args);
}
}
};
//定时器版
function throttle(fun, wait) {
let timeout = null;
return function () {
let context = this;
let args = [...arguments]
if (!timeout) {
timeout = setTimeout(() => {
fun.apply(context, args)
timeout = null
}, wait)
}
}
} 版权声明 : 本文未使用任何知识共享协议授权,您可以任何形式自由转载或使用。

发表评论 / 取消回复