throttle.ts 473 B

1234567891011121314151617
  1. /**
  2. * 按调用次数做节流
  3. * @param {Function} fn 真正要执行的函数
  4. * @param {number} count 每累计调用 count 次才执行 1 次
  5. * @returns {Function} 包装后的节流函数
  6. */
  7. export function throttleCount(fn, count) {
  8. if (count <= 0) throw new RangeError('count must > 0');
  9. let counter = 0;
  10. return function (...args) {
  11. counter += 1;
  12. if (counter >= count) {
  13. counter = 0;
  14. return fn.apply(this, args);
  15. }
  16. };
  17. }