index.js 750 B

12345678910111213141516171819202122232425262728293031
  1. /**
  2. * Module exports.
  3. */
  4. module.exports = throttle;
  5. /**
  6. * Returns a new function that, when invoked, invokes `func` at most one time per
  7. * `wait` milliseconds.
  8. *
  9. * @param {Function} func The `Function` instance to wrap.
  10. * @param {Number} wait The minimum number of milliseconds that must elapse in between `func` invokations.
  11. * @return {Function} A new function that wraps the `func` function passed in.
  12. * @api public
  13. */
  14. function throttle (func, wait) {
  15. var rtn; // return value
  16. var last = 0; // last invokation timestamp
  17. return function throttled () {
  18. var now = new Date().getTime();
  19. var delta = now - last;
  20. if (delta >= wait) {
  21. rtn = func.apply(this, arguments);
  22. last = now;
  23. }
  24. return rtn;
  25. };
  26. }