Open EdwardZZZ opened 7 years ago
class Trigger {
static list = [];
static run(fn) {
const { list } = Trigger;
list.push(fn)
Promise.resolve().then(() => {
if (list.length === 0) return;
list[list.length - 1]();
list.length = 0;
})
}
}
[...Array(10)].forEach((_, i) => {
Trigger.run(() => {
console.log('1', i);
});
});
[...Array(10)].forEach((_, i) => {
Trigger.run(() => {
console.log('2', i);
});
});
setTimeout(()=> {
[...Array(10)].forEach((_, i) => {
Trigger.run(() => {
console.log('3', i);
});
});
});
function debounceMicro() {
const list = [];
return function(fn) {
list.push(fn)
Promise.resolve().then(() => {
if (list.length === 0) return;
list[list.length - 1]();
list.length = 0;
});
}
}
const trigger = debounceMicro();
[...Array(10)].forEach((_, i) => {
trigger(() => {
console.log('11', i);
});
});
[...Array(10)].forEach((_, i) => {
trigger(() => {
console.log('12', i);
});
});
setTimeout(()=> {
[...Array(10)].forEach((_, i) => {
trigger(() => {
console.log('13', i);
});
});
});
function useThrottle(cb, delay) {
const options = {
leading: true,
trailing: false
}; // add custom lodash options
const cbRef = useRef(cb);
// use mutable ref to make useCallback/throttle not depend on `cb` dep
useEffect(() => {
cbRef.current = cb;
});
return useCallback(
throttle((...args) => cbRef.current(...args), delay, options),
[delay]
);
}
function useDebounce(cb, delay) {
const inputsRef = useRef(cb); // mutable ref like with useThrottle
useEffect(() => {
inputsRef.current = {
cb,
delay
};
}); //also track cur. delay
return useCallback(
debounce((...args) => {
// Debounce is an async callback. Cancel it, if in the meanwhile
// (1) component has been unmounted (see isMounted in snippet)
// (2) delay has changed
if (inputsRef.current.delay === delay && isMounted())
inputsRef.current.cb(...args);
}, delay, options),
[delay, debounce]
);
}
简单实现