H246802 / 30-days-challenge

30天每日打卡
4 stars 0 forks source link

day-28-函数防抖 #28

Open H246802 opened 5 years ago

H246802 commented 5 years ago

写一个 debounce 函数,可以按照如下方式调用,实现的效果是:当连续滚动窗口时,滚动停下300ms后才执行 print 函数

function debounce(fn, time) {
  // your code
}
function print() {
  console.log('print')
}
window.addEventListener('scroll', debounce(print, 300))
H246802 commented 5 years ago

函数防抖:通过闭包保存计时器的id,与函数节流类似

function debounce(fn, time){
  var clock = null;
  return function(){
    clearTimeout(clock);
    clock = setTimeout(function(){
      fn();
    }, time);
  };
}

function print() {
  console.log('print');
}

window.addEventListener('scroll', debounce(print, 300));