//防抖函数
function debounce(func,delay) {
let timeoutId
return function(...args) {
//这里的this指向的是input这个对象
let context =this
clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
func.apply(context,args)
},delay)
}
}
const debounceFn = debounce(function() {
//这里执行要进行防抖的具体操作
},500)
Element.addEventerListener('input',debounceFn)
//节流函数
function throttle(func,delay) {
let canRun = true
return function(...args) {
if(canRun) {
const context = this
canRun = false
func.apply(context,args)
setTimeout(() => {
canRun = true
},delay)
}
}
}
const = throttleFn = throttle(function() {
//这里执行要进行节流的具体操作
},1000)
Element.addEventerListener('scroll',throttleFn)
上面的代码中都绑定了this和arguments,下面将展示使用this和arguments的简单场景
//传递参数的场景
function debounce(fn, delay) {
let timer = null;
return function(...args) {
const context = this;
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
function sayHello(name) {
console.log(`Hello, ${name}!`);
}
const debouncedSayHello = debounce(sayHello, 500);
// 调用防抖函数,并传递参数
Element.addEventerListener('input',debounceFn('KangKang')
//需要使用this的场景
function debounce(fn, delay) {
let timer = null;
return function(...args) {
const context = this;
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
function handleInput(input) {
console.log(`Input value: ${input.value}`);
}
const inputElement = document.getElementById('myInput');
// 创建一个带防抖功能的事件处理函数
const debouncedHandleInput = debounce(handleInput, 500);
// 添加事件监听器
inputElement.addEventListener('input', function() {
debouncedHandleInput(this); // 将input对象作为参数传递给防抖函数
});