参考文章:
在学习函数防抖、节流的时候遇到一个疑惑
var button = document.getElementsByClassName('button')[0];
button.addEventListener('click',
debounce(() => {
console.log('点完了')})
)
function debounce(fn, interval = 300) {
let timeout = null;
return function () {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, interval);
};
}
debounce函数返回的是一个函数,并没有写此函数执行的语句,为什么返回一个函数就会执行呢?
问了大佬才知道,原因在于addEventListener接收的是debounce返回的函数,点击button的时候会执行addEventListener('event',fn,false) 这个fn,而fn是debounce(),即debounce函数执行完之后return的子函数(假设为A)。点击的时候执行A函数。
function throttle(fn, interval = 300) {
let canRun = true;
return function () {
if (!canRun) return;
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;
}, interval);
};
}
function onScroll(){
console.log("scroll");
}
window.scroll = throttle(onScroll);
//疑惑? : 滚动条滚动的时候岂不是每次都执行throttle(onScroll) 吗?
//那就是每次都执行 let canRun = true 了呀???
throttle函数只有在赋值给window.scroll 的时候执行了一次,window.scroll接收到的是throttle里return的函数
不知道arguments有什么用?传参是什么?
function testThrottle(e, content) {
console.log(e, content);
}
var testThrottleFn = throttle(testThrottle, 1000); // 节流函数
document.onmousemove = function (e) {
testThrottleFn(e, 'throttle'); // 给节流函数传参
}
//参考 https://segmentfault.com/a/1190000018445196