节流(一段时间执行一次之后,就不执行第二次)

  1. function throttle(fn, delay){
  2. let canUse = true
  3. return function(){
  4. if(canUse){
  5. fn.apply(this, arguments)
  6. canUse = false
  7. setTimeout(()=>canUse = true, delay)
  8. }
  9. }
  10. }
  11. const throttled = throttle(()=>console.log('hi'))
  12. throttled()
  13. throttled()

防抖(一段时间会等,然后带着一起做了)

  1. function debounce(fn, delay){
  2. let timerId = null
  3. return function(){
  4. const context = this
  5. if(timerId){window.clearTimeout(timerId)}
  6. timerId = setTimeout(()=>{
  7. fn.apply(context, arguments)
  8. timerId = null
  9. },delay)
  10. }
  11. }
  12. const debounced = debounce(()=>console.log('hi'))
  13. debounced()
  14. debounced()