节流(throttle)
function throttle(fn, delay = 500) {
if ((typeof fn) !== "function") {
throw new Error(`${fn} not a function,you hvae to pass in a function `);
}
if ((typeof delay) !== "number") {
throw new Error(`${delay} not a number,you hvae to pass in a number `);
}
let timer = null;
return function() {
if (timer) {
return;
}
timer = setTimeout(function() {
fn.call(this, arguments);
clearTimeout(timer);
timer = null;
}, delay)
}
}
防抖(deBounce)
function throttle(fn, delay = 500) {
if ((typeof fn) !== "function") {
throw new Error(`${fn} not a function,you hvae to pass in a function `);
}
if ((typeof delay) !== "number") {
throw new Error(`${delay} not a number,you hvae to pass in a number `);
}
let timer = null;
return function() {
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function() {
fn.call(this, arguments);
clearTimeout(timer);
timer = null;
}, delay)
}
}