27 lines
648 B
JavaScript
27 lines
648 B
JavaScript
|
|
/**
|
|||
|
|
* 防抖函数
|
|||
|
|
* @param {Function} func - 需要防抖的函数
|
|||
|
|
* @param {number} wait - 延迟时间,单位毫秒
|
|||
|
|
* @param {boolean} immediate - 是否立即执行
|
|||
|
|
* @returns {Function} - 防抖后的函数
|
|||
|
|
*/
|
|||
|
|
export function debounce(func, wait, immediate = false) {
|
|||
|
|
let timeout;
|
|||
|
|
|
|||
|
|
return function executedFunction(...args) {
|
|||
|
|
const later = () => {
|
|||
|
|
timeout = null;
|
|||
|
|
if (!immediate) func.apply(this, args);
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
const callNow = immediate && !timeout;
|
|||
|
|
|
|||
|
|
clearTimeout(timeout);
|
|||
|
|
|
|||
|
|
timeout = setTimeout(later, wait);
|
|||
|
|
|
|||
|
|
if (callNow) func.apply(this, args);
|
|||
|
|
};
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export default debounce;
|