函数防抖

一个函数在被触发的 n 秒后再执行(延迟执行), 如果 n 秒内再次被触发,计时器则重新开始计时。

  1. /**
  2. * debounce
  3. * @param {Function} fn 需要进行防抖的函数
  4. * @param {Number} delay 延迟的时间 ms
  5. * @param {Boolean} triggerNow 首次是否立即触发
  6. */
  7. function debounce (fn, delay, triggerNow) {
  8. var t = null;
  9. return function () {
  10. var _this = this,
  11. args = arguments;
  12. if (t) {
  13. clearTimeout(t);
  14. }
  15. if (triggerNow) {
  16. var exec = !t;
  17. t = setTimeout(function () {
  18. t = null;
  19. }, delay);
  20. if (exec) {
  21. fn.apply(_this, args);
  22. }
  23. } else {
  24. t = setTimeout(function () {
  25. fn.apply(_this, args);
  26. }, delay)
  27. }
  28. }
  29. }

节流函数

一个函数在被触发后的 n 秒内如果再次触发,不执行。

  1. /**
  2. * throttle
  3. * @param {Function} fn 需要进行节流的函数
  4. * @param {Number} delay 延迟的时间 ms
  5. */
  6. function throttle (fn, delay) {
  7. var t = null,
  8. begin = new Date().getTime();
  9. return function () {
  10. var _this = this,
  11. args = arguments,
  12. cur = new Date().getTime();
  13. if (t) {
  14. clearTimeout(t);
  15. }
  16. if (cur - begin < delay) {
  17. t = setTimeout(function () {
  18. fn.apply(_this, args);
  19. }, delay)
  20. } else {
  21. fn.apply(_this, args);
  22. begin = cur;
  23. }
  24. }
  25. }