throttle.js 751 B

1234567891011121314151617181920212223
  1. // 节流函数: 连续不断地触发某事件(如点击),只在单位时间内只触发一次
  2. // throttle和debounce均是通过减少实际逻辑处理过程的执行来提高事件处理函数运行性能的手段,并没有实质上减少事件的触发次数。
  3. export default function throttle(fun, delay=2000) {
  4. let last, deferTimer
  5. return function (args) {
  6. let that = this;
  7. let _args = arguments;
  8. let now = +new Date();
  9. if(last && now < last + delay) {
  10. clearTimeout(deferTimer);
  11. deferTimer = setTimeout(function () {
  12. last = now;
  13. fun.apply(that, _args);
  14. },delay)
  15. } else {
  16. last = now;
  17. fun.apply(that,_args);
  18. }
  19. }
  20. }