throttle.js 677 B

123456789101112131415161718192021222324252627282930
  1. /**
  2. * @desc 节流函数
  3. * @param {Function} callBack
  4. * @return {Function} fn
  5. */
  6. const throttle = function (fn, delay = 500) {
  7. let _self = fn, //需要被延迟执行的函数引用
  8. timer,
  9. firstTime = true; //是否第一次调用
  10. return function () {
  11. let args = arguments;
  12. if (firstTime) { //第一次调用不用延迟
  13. _self.apply(this, args);
  14. firstTime = false;
  15. }
  16. if (timer) { //timer还在没结束前一次
  17. return false;
  18. }
  19. timer = setTimeout(() => { //延迟执行
  20. clearTimeout(timer);
  21. timer = null; //手动释放timer
  22. _self.apply(this, args);
  23. }, delay);
  24. }
  25. };
  26. module.exports = throttle