防抖函数(触发高频事件后 n 秒内函数只会执行一次,如果 n 秒内高频事件再次被触发,则重新计算时间)
export function debounce(func, delay) {
let timer = null;
return function(...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
节流函数(高频事件触发,但在 n 秒内只会执行一次,所以节流会稀释函数的执行频率)
export function throttle(func, delay) {
let timer = Date.now();
return function(...args) {
let now = Date.now();
if (now - timer > delay) {
func.apply(this, args);
timer = Date.now();
}
};
}
闭包函数(可以访问函数内部的变量)
function fn() {
let a = 10;
function b() {
a = a * 10;
return a;
}
return b;
}
var baz = fn();
console.log(baz());
console.log(baz());
console.log(baz());