Open yang-xianzhu opened 1 year ago
定时器版
时间戳版
// 定时器版 function throttle(fn: Function, wait: number = 500) { let timeId: null | number = null; return function (...args: Array<any>) { if (timeId) { return; } timeId = setTimeout(() => { fn.apply(this, args); timeId = null; }, wait); }; } // 时间戳版 function throttle(fn: Function, wait: number = 500) { // 记录上一次时间戳 let prevTime = Date.now(); return function (...args: Array<any>) { // 获取当前时间戳 let currentTime = Date.now(); if (currentTime - prevTime >= wait) { fn.apply(this, args); prevTime = currentTime; } }; }
可立即执行版
// 定时器版 function debounce(fn: Function, wait: number = 500) { let timeId: null | number = null; return function (...args: Array<any>) { if (timeId) { clearTimeout(timeId); } timeId = setTimeout(() => { fn.apply(this, args); }, wait); }; } // 可立即执行版 function debounce(fn: Function, wait: number = 500, immediate: boolean = true) { let timeId: null | number = null; return function (...args: Array<any>) { if (timeId) clearTimeout(timeId); // 如果是立即执行 if (immediate) { let callNow = !timeId; timeId = setTimeout(() => { timeId = null; }, wait); if (callNow) { fn.apply(this, args); } return; } timeId = setTimeout(() => { fn.apply(this, args); }, wait); }; }
定时器版
、时间戳版
。定时器版
、可立即执行版
。