console
function debounce(fn, time) {
if (typeof fn !== 'function') {
throw new TypeError('Expected a function');
}
let timer = null;
return function() {
const context = this;
const args = arguments;
if (!time && time !== 0 && typeof window.requestAnimationFrame === 'function') {
console.log('window.requestAnimationFrame');
window.cancelAnimationFrame(timer);
timer = window.requestAnimationFrame(() => {
fn.apply(context, args);
});
return;
}
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, time);
}
}
function throttle(fn, time) {
if (typeof fn !== 'function') {
throw new TypeError('Expected a function');
}
let isFirstInvoke = true;
let timerId = null;
return function() {
const args = arguments;
const context = this;
if (isFirstInvoke) {
fn.apply(context, args);
isFirstInvoke = false;
}
if (timerId) {
return;
}
timerId = setTimeout(function(){
clearTimeout(timerId);
fn.apply(context, args);
timerId = null;
}, time )
}
}
function test(a) {
console.log(a);
}
const transferFn = debounce(test);
const btn = document.getElementById('button');
btn.addEventListener('click', () => {
transferFn(222)
});
<button id="button">按钮</button>