js防抖可以让被调用的函数在连续高频操作过程中只调用一次,使用场景:有oninput, onmousemove, onscroll, onresize等事件。实现如下:
function debounce (callback, delay = 1000) {
let timer = null;
return function () {
// 因为这里返回出去的方法是被 外部元素调用的,
// 所以这里的 this 就指向了外部元素
let self = this;
// 每个函数内部都一个属性 arguments, 其中包括了所有外部调用这个函数传递进来的参数
let args = arguments;
timer && clearTimeout(timer)
timer = setTimeout(function () {
// apply: 作用就是改变方法内部this的指向, 并能将参数传递给该方法, 最后立即执行这个函数
callback.apply(self, args)
}, delay);
}
}
// 使用
let onInput = document.queryInput('input');
onInput = debounce (function(args){
console.log(this)
console.log(args)
}, 2000)
网友评论