throttle 节流

在一定的时间范围内只执行一次

  1. const throttle = function(fn, delay) {
  2. let previous = 0;
  3. let timer = null;
  4. return function run(... args) {
  5. const now = new Date();
  6. const remaining = delay - (now - previous);
  7. //间隔时间超过delay则立马执行
  8. //remaining > delay指的是客户端修改了时间,导致remianing > delay也会立马执行
  9. if (remaining < 0 || remaining > delay) {
  10. previous = now;
  11. fn.call(this, args);
  12. } else if (!timer) {
  13. timer = setTimeout(() => {
  14. previous = new Date();
  15. clearTimeout(timer);
  16. timer = null;
  17. fn.call(this, args);
  18. }, remaining);
  19. }
  20. };
  21. };

debounce防抖

在一定时间内若重复操作,则重新计算开始时间

  1. function debounce(fn, delay) {
  2. let previous = 0;
  3. let timer = null;
  4. return function proxy(...args) {
  5. if (!timer) {
  6. timer = setTimeout(() => {
  7. previous = new Date();
  8. clearTimeout(timer);
  9. timer = null;
  10. fn.call(this, args)
  11. },delay);
  12. }
  13. }
  14. }