debounce.js 582 B

1234567891011121314151617181920212223242526272829
  1. const title = document.getElementById('title')
  2. // let timer = null
  3. // title.addEventListener('keyup', function () {
  4. // if(timer) {
  5. // clearTimeout(timer)
  6. // }
  7. // timer = setTimeout(()=>{
  8. // console.log(title.value)
  9. // timer = null
  10. // }, 500)
  11. // })
  12. // 防抖
  13. function debounce(fn, delay = 500) {
  14. let timer = null
  15. return function () {
  16. if(timer)clearTimeout(timer)
  17. timer = setTimeout(()=>{
  18. fn.apply(this, arguments)
  19. timer = null
  20. }, delay)
  21. }
  22. }
  23. title.addEventListener('keyup', debounce(function (){
  24. console.log(this.value)
  25. }, 500))