基础版防抖

// 防抖的意思是我要在n秒钟之后执行XXX,如果在n秒内执行了那就重新执行.

function debounce(fn, timing = 1000) {
  var time
  return function (...args) {
    clearTimeout(time)
    const that = this
    time = setTimeout(() => {
      fn.apply(that, ...args)
    }, timing);
  }
}

const a = debounce(() => {
  console.log('执行');
}, 1000)

a()
a()
a()
a()

立即执行版防抖

function debounce(fn, timing) {
  var time
  let flag = false
  return (...args) => {
    const that = this
    if (!flag) {
      fn.apply(that, ...args)
      flag = true
    }
    clearTimeout(time)
    time = setTimeout(() => {
      flag = false
    }, timing);
  }
}

const aaa = debounce(function () {
  console.log('立即执行');
}, 2000)

aaa()
setTimeout(() => {
  aaa()
}, 1000);

基础版节流

function throttling(fn, wait = 0) {
  let flag = true
  return (...args) => {
    if (flag) {
      flag = false
      time = setTimeout(() => {
        fn.apply(this, ...args)
        flag = true
      }, wait)
    }
  }
}

function log() {
  console.log(111);
}
const a = throttling(log, 2000)
a()
setTimeout(() => {
  a()
}, 3000);

立即执行版节流

function throttling(fn, timing) {
  let flag = true
  return (...args) => {
    if (flag) {
      flag = false
      fn.apply(this, ...args)
      setTimeout(() => {
        flag = true
      }, timing);
    }
  }
}


function log() {
  console.log('节流');
}

const a = throttling(log, 1000)
a()
a()
a()
a()
setTimeout(() => {
  a()
}, 1000);
Last modification:March 10, 2021
If you think my article is useful to you, please feel free to appreciate