blog icon indicating copy to clipboard operation
blog copied to clipboard

函数防抖 与 函数节流

Open YuArtian opened this issue 5 years ago • 0 comments

函数防抖 与 函数节流

书写 debounce 函数 实现函数防抖功能

function debounce (fn, delay) {
  var timeout
  return function() {
    clearTimeout(timeout)
    timeout = setTimeout(fn.bind(this, ...arguments),delay)
  }
}

当然,现实中你可能有一个 input 或者 button 需要做防抖处理

var validate = debounce(function(event){
  console.log('validate event',event);
  console.log('this',this);
  console.log('change !', new Date);
}, 1000)

document.querySelector('#button').addEventListener('click', validate)
document.querySelector('#input').addEventListener('input', validate)

无论中间点击了多少次,都以 1s 的延迟 执行最后一次。

书写 throttle 函数实现函数节流

function throttle (fn, during) {
  var timeout
  var start = new Date().valueOf()
  var during = during || 200
  return function () {
    var current = new Date().valueOf()
    clearTimeout(timeout)
    if (current - start >= during) {
      fn.apply(this, arguments)
      start = current
    } else {
      timeout = setTimeout(fn.bind(this, arguments), during)
    }
  }
}

节流就是限制设定的方法在规定的时间段内只能触发一次。

例如拖拽动画或者鼠标移动时适用。

YuArtian avatar Dec 04 '18 14:12 YuArtian