fish519 / note

Write down problems encountered during development and take notes on how to solve them
0 stars 0 forks source link

防抖和节流 #3

Open fish519 opened 5 years ago

fish519 commented 5 years ago

确保最后的能执行,flush

fish519 commented 5 years ago
const debounce = (fn, time) => {
  let timeout = null;
  return () => {
    clearTimeout(timeout);
    timeout = setTimeout(function() {
      fn.apply(this, arguments)
    }, time)
  }
}

n秒内执行最后一次

const throttle = (fn, time) => {
  let canRun = true;
  return function(){
    if(!canRun) return;
    fn.apply(this, arguments);
    canRun = false;
    setTimeout(() => {
      canRun = true;
    }, time);
  }
}

n秒内执行一次