小程序的防抖节流怎么写?

18 篇文章 0 订阅

1.概念

函数防抖(debounce)

函数防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

简单的说,当一个动作连续触发,则只执行最后一次

如果有人进电梯(触发事件),那电梯将在10秒钟后出发(执行事件监听器),这时如果又有人进电梯了(在10秒内再次触发该事件),我们又得等10秒再出发(重新计时)

函数节流(throttle)

限制一个函数在一定时间内只能执行一次。

保证如果电梯第一个人进来后,10秒后准时运送一次,这个时间从第一个人上电梯开始计时,不等待,如果没有人,则不运行

2. 代码封装

函数防抖(debounce)

/**
 *
 * @param {*} cb 回调函数
 * @param {*} delay 延时时间
 */
const debounce = (cb, delay = 1000) => {
  let timer = null;
  return function() {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      cb.apply(this, arguments);
    }, delay);
  };
};

函数节流(throttle)

/**
 *
 * @param {*} cb 回调函数
 * @param {*} wait 等待时间
 */
const throttle = (cb, delay = 1000) => {
  //距离上一次的执行时间
  let lastTime = 0;
  return function() {
    let _this = this;
    let _arguments = arguments;
    let now = new Date().getTime();
    //如果距离上一次执行超过了delay才能再次执行
    if (now - lastTime > delay) {
      cb.apply(_this, _arguments);
      lastTime = now;
    }
  };
};

3. 使用

mine.axml

<view class="root_container">
  
  <input placeholder="Input" onInput="inputHandle" />

  <button size="default" type="primary" catchTap='clickHandle'>Button</button>
</view>

mine.js

import { debounce, throttle } from "/utils/index.js";

  // 节流使用
  clickHandle: throttle(function(...args) {
    console.log("throttle", args);
    console.log("throttle", this);
  }, 2000),

  // 防抖使用
  inputHandle: debounce(function(...args) {
    console.log("debounce args", args);
    console.log("debounce this", this);
  }, 1000),
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值