image.png

防抖

  1. const debounce = (fn, delay) => {
  2. //存放定时器
  3. let inDebounce;
  4. //高阶函数返回值
  5. return function (...args) {
  6. const context = this;
  7. //清除上一次定时器
  8. clearTimeout(inDebounce);
  9. inDebounce = setTimeout(() => {
  10. //修改传递进来函数的this指向和参数
  11. fn.apply(context, args);
  12. }, delay)
  13. }
  14. };
  15. //触发debounce获取return回的函数
  16. const debounceFn = debounce(ajaxFn, 1000);
  17. //需要被触发的函数
  18. function ajaxFn(data) {
  19. console.log(data)
  20. }
  21. //点击按钮触发测试
  22. function btnClick() {
  23. debounceFn("相当于调用了ajaxFn")
  24. }

节流

  1. function throttle(fun, delay) {
  2. let last; //上一次点击时间
  3. let deferTimer; //定时器
  4. return function(...args){
  5. let that = this
  6. let now=+new Date();//获取当前时间(number)
  7. if(last && now < last +delay){ //未在规定时间内
  8. clearTimeout(deferTimer)
  9. deferTimer=setTimeout(()=>{
  10. last=now;//执行后重新赋值last
  11. fun.apply(that,args)
  12. },delay)
  13. }else{ //初始和规定时间内
  14. last=now
  15. fun.apply(that,args)
  16. }
  17. }
  18. };
  19. //触发debounce获取return回的函数
  20. const throttleFn = throttle(ajaxFn, 1000);
  21. //需要被触发的函数
  22. function ajaxFn2(data) {
  23. console.log(data)
  24. }
  25. //点击按钮触发测试
  26. function btnClick2() {
  27. throttleFn("相当于调用了ajaxFn2")
  28. }