防抖
作用:在多次触发事件的情况下,只执行一次

第一版

  1. var debounce = function(func){
  2. let timer;
  3. return function(){
  4. if(timer){clearTimeout(timer)}
  5. timer = setTimeout(() => {
  6. // func()
  7. console.log(this)
  8. func.apply(this)
  9. },1000)
  10. }
  11. }
  12. var fun1 = function(){
  13. console.log(this)
  14. }
  15. var debounceTask = debounce(fun1)
  16. var input = document.getElementById('input')
  17. input.addEventListener('keydown',debounceTask)

思路
首先定义一个变量 用于接收创建定时器的id,方便清除定时器
在设置定时器前,先判断是否之前创建的定时器存在,如果存在就清除

问题
没有绑定this
没有使用apply之前,this默认指向window
使用apply之后,this就会指向函数执行的环境

第二版

  1. var debounce = function(func,wait){
  2. let timer;
  3. return function(...args){
  4. if(timer){clearTimeout(timer)}
  5. timer = setTimeout(() => {
  6. func.apply(this,args)
  7. },wait)
  8. }
  9. }

优化
两种情况:
1.用户在搜索问题时连续输入内容,在输入最后一个字符时执行函数,函数执行时间间隔小于指定的时间。
2.用户在star时,需要第一时间看到反馈,此函数需要立即执行,反馈情况给用户看,下一次调用时间间隔必须大于wait才会触发

  1. var button = document.getElementById('button');
  2. var start = document.getElementById('star')
  3. var divstatue = function(){
  4. if(start.style.background == 'red'){
  5. start.style.background = 'blue';
  6. console.log(this)
  7. }else{
  8. start.style.background = 'red';
  9. console.log(this)
  10. }
  11. }
  12. var debounce2 = function(func,wait){
  13. var context,arg;
  14. var timer
  15. var later = function(){
  16. timer = setTimeout(() => {
  17. timer = null
  18. func.apply(context,timer)
  19. }, wait);
  20. }
  21. return function(...args){
  22. context = this
  23. arg = args;
  24. if(!timer){
  25. func.apply(context,arg)
  26. }else{
  27. later()
  28. }
  29. }
  30. }
  31. var debounceTask2 = deboncetest3(divstatue,1000)
  32. button.addEventListener('click',debounceTask2)