美文网首页
防抖与节流

防抖与节流

作者: narcissus灬 | 来源:发表于2019-11-14 11:30 被阅读0次

防抖是任务频繁触发的情况下,只有任务触发的间隔超过指定间隔的时候,任务才会执行,一般用于输入框实时搜索

// 防抖函数
function debounce(fn, time) {
  let timer = null
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments)
    }, time)
  }
}

// 测试防抖
function testDebounce() {
  // 定义一个需要执行的函数
  function fn(i) {
    // 里面有很多很多操作
    console.log('fn', i)
  }
  // 对fn注册防抖函数
  let debounceFn = debounce(fn, 1000)

  let index = 0
  let itimer = setInterval(() => {
    index++
    console.log('setInterval: ', index)
    if(index == 10){
      clearTimeout(itimer)
    }
    debounceFn(index)
    // 第一次执行时,timer=null,执行timer赋值
    // 第二次执行timer等于上一次的赋值,由于上次执行需要在time时间后,还未执行就被清除,并在次赋值
    // 第三次同第二次
    // ...
    // 直到某次与上一次执行时间超过了time时间,才会真正的执行fn操作函数
  }, 500)
}

// 未使用防抖函数
function test() {
  function fn(i) {
    console.log(i)
  }
  let index = 0
  let itimer = setInterval(() => {
    index++
    console.log('setInterval: ', index)
    if(index == 10){
      clearTimeout(itimer)
    }
    fn(index)
  }, 500)
}

// test()
// testDebounce()

节流是规定函数在指定的时间间隔内只执行一次
立即执行第一次,下一次会在超出指定时间后执行

// 节流函数   立即执行第一次,下一次会在超出指定时间后执行
function throttle(fn, time = 500) {
  let last
  return function () {
    let args = arguments
    let now = new Date()
    if (!last || now - last > time) {
      last = now
      fn.apply(this, args)
    }
  }
}

/*
// 节流函数   不会立即执行第一次,在指定时间后执行第一次
function throttle(fn, time) {
  let canRun = true
  return function () {
    if (!canRun) {
      return
    }
    canRun = false
    setTimeout(() => {
      fn.apply(this, arguments)
      canRun = true
    }, time)
  }
}
*/

// 测试节流
function testThrottle() {
  // 定义一个需要执行的函数
  function fn(i) {
    // 里面有很多很多操作
    console.log('fn', i)
  }
  // 对fn注册防抖函数
  let throttleFn = throttle(fn, 1000)
  let index = 0
  setInterval(() => {
    index++
    console.log('setInterval: ', index)
    throttleFn(index)
  }, 500);
}

testThrottle()

相关文章

网友评论

      本文标题:防抖与节流

      本文链接:https://www.haomeiwen.com/subject/qiolictx.html