zoukankan      html  css  js  c++  java
  • 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) } }

      

  • 相关阅读:
    02_类和对象
    Django_数据库增删改查——增
    Django_同步数据库
    Django_models类属性。
    CSS_垂直居中
    CSS_背景属性
    CSS_定位
    CSS_浮动
    CSS_盒子模型
    CSS_元素的分类
  • 原文地址:https://www.cnblogs.com/jingxuan-li/p/14638080.html
Copyright © 2011-2022 走看看