JavaScript之 函数节流(Throttling) 与 防抖(Debounce)

Throttling:在监听鼠标移动事件、盒子滚动事件等使用节流技术能节省性能消耗
/**
 * 节流函数(每隔t执行一次)
 */
function Throttling(fn, t) {
    const timer = null

    return function() {
      // 执行完上一次的内容后才执行下一次的内容 if(!timer) { const arg = arguments const context = this timer = setTimeout(() => { fn.apply(context, arg)
           // 或使用 clearTimeout(timer),清除计时器 timer = null }, t) } } }

Debounce:在实现输入框联想搜索时,可以等到输入完之后在进行联想搜索,避免频繁发送请求消息造成卡顿
/**
 * 防抖函数(只执行最后一次)
 */
function Debounce(fn, t) {
    const timer = null

    return function() {
// 如果计时器已经存在,那么取消此次执行 timer && clearTimeout(timer) const context = this const arg = arguments // 执行计时器 timer = setTimeout(() => { fn.apply(context, arg) clearTimeout(timer) }, t) } }

  

posted @ 2021-04-09 17:23  C+V-Engineer  阅读(165)  评论(0编辑  收藏  举报