防抖

image.png

  1. let ipt = document.querySelector('input')
  2. let btn = document.querySelector('button')
  3. // 封装一个debounce函数,实现防抖功能(频率很快的时候只执行最后一次)
  4. function debounce(fn) {
  5. console.log('键盘还没按呢');
  6. let timerId = null
  7. // 调用完debounce之后就会得到这个函数,这个函数内部有一个变量timerId,它是保存在一个闭包中的
  8. return function () {
  9. clearTimeout(timerId)
  10. timerId = setTimeout(() => {
  11. // 此处的this就是事件绑定的那个dom对象
  12. console.log(this);
  13. // 将fn内部的this改成事件绑定的那个dom对象
  14. fn.call(this)
  15. // fn.apply(this)
  16. // fn.bind(this)() // 这里不太合适
  17. }, 300)
  18. }
  19. }
  20. function search() {
  21. console.log('search', this);
  22. }
  23. function like() {
  24. console.log('一键三连', this);
  25. }
  26. ipt.addEventListener('keyup', debounce(search))
  27. btn.addEventListener('click', debounce(like))

节流

image.png

  1. let box = document.querySelector('.box')
  2. // 节流
  3. // 封装一个throttle函数,实现节流功能( 频率很快的时候,速度均匀的运行)
  4. function throttle(fn , ...args) {
  5. // 通过闭包保存一个变量 这个变量用于设置定时的开关 默认是开着的
  6. let isOpen = true
  7. return function () {
  8. // 当开关没有开的时候,就返回,不执行后面的定时器了。只有当后面的定时器执行完成之后,开关才重新打开
  9. if (!isOpen) return
  10. // 当滚动时,立马把开关关起来,开启一个定时器
  11. isOpen = false
  12. setTimeout(() => {
  13. // 时间到了执行逻辑
  14. fn.call(this,args)
  15. // 时间到了,重新打开开关
  16. isOpen = true
  17. }, 100)
  18. }
  19. }
  20. function gundong(...arr) {
  21. console.log(`${arr}在滚动box盒子`, this);
  22. }
  23. box.addEventListener('scroll', throttle(gundong , 'jake','rose'))
  24. // box.addEventListener('scroll', gundong)