防抖debounce.js 587 B

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