关于javascript:函数防抖和节流

防抖与节流

函数防抖

在函数被触发后提早某个时间段后触发,如果在该时间段内再次触发,则从新计时

简略实现

// 防抖函数
function debounce(fun, delay) {
  let record = null
  return (...content) => {
    if (record) {
      clearTimeout(record)
    }
    record = setTimeout(() => {
        fun(...content)
    }, delay)
  }
}

函数节流

在一个时间段内一个函数屡次被触发,只有一次会失效

简略实现

// 节流函数
function throttle(fun, delay) {
  let record = null
  return (...content) => {
    if (!record) {
      record = setTimeout(() => {
        fun(...content)
        clearTimeout(record)
        record = null
      }, delay)
    }
  }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理