index.js 615 B

12345678910111213141516171819202122232425262728293031323334
  1. module.exports = debounce;
  2. function debounce(fn, delay, atStart, guarantee) {
  3. var timeout;
  4. var args;
  5. var self;
  6. return function debounced() {
  7. self = this;
  8. args = Array.prototype.slice.call(arguments);
  9. if (timeout && (atStart || guarantee)) {
  10. return;
  11. } else if (!atStart) {
  12. clear();
  13. timeout = setTimeout(run, delay);
  14. return timeout;
  15. }
  16. timeout = setTimeout(clear, delay);
  17. fn.apply(self, args);
  18. function run() {
  19. clear();
  20. fn.apply(self, args);
  21. }
  22. function clear() {
  23. clearTimeout(timeout);
  24. timeout = null;
  25. }
  26. };
  27. }