index.js 820 B

1234567891011121314151617181920212223242526272829303132
  1. module.exports = throttle;
  2. /**
  3. * Returns a new function that, when invoked, invokes `func` at most once per `wait` milliseconds.
  4. *
  5. * @param {Function} func Function to wrap.
  6. * @param {Number} wait Number of milliseconds that must elapse between `func` invocations.
  7. * @return {Function} A new function that wraps the `func` function passed in.
  8. */
  9. function throttle (func, wait) {
  10. var ctx, args, rtn, timeoutID; // caching
  11. var last = 0;
  12. return function throttled () {
  13. ctx = this;
  14. args = arguments;
  15. var delta = new Date() - last;
  16. if (!timeoutID)
  17. if (delta >= wait) call();
  18. else timeoutID = setTimeout(call, wait - delta);
  19. return rtn;
  20. };
  21. function call () {
  22. timeoutID = 0;
  23. last = +new Date();
  24. rtn = func.apply(ctx, args);
  25. ctx = null;
  26. args = null;
  27. }
  28. }