简单的节流函数实现

 function throttle(callback, duration) {
        console.log(this);

        let time;
        return function (data) {
          console.log(this);
          if (!time) {
            time = setTimeout(() => {
              console.log(this);
              callback.apply(this, arguments);
            }, duration);
            time = null;
          }
        };
      }
      function fn(params) {
        console.log(params);
      }
      let func = throttle(fn, 1000);
      console.log(func("你好"));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
防抖和节流都是用来控制函数执行频率的方法,但它们的实现和应用场景有所不同。 防抖函数的作用是在指定的时间间隔内,如果函数被连续调用多次,则只执行最后一次调用,并将其延迟到指定时间后执行。常见的应用场景是在用户输入频繁的情况下进行搜索或请求数据,以减少不必要的请求或计算。 一个简单的防抖函数可以这样实现: ```python import time def debounce(delay): def decorator(func): last_called = time.time() def wrapper(*args, **kwargs): nonlocal last_called now = time.time() if now - last_called < delay: return last_called = now return func(*args, **kwargs) return wrapper return decorator ``` 使用示例: ```python @debouce(0.5) def search(keyword): # 模拟搜索操作 print("正在搜索:", keyword) search("apple") search("banana") time.sleep(1) search("cat") ``` 上述代码中,`debounce` 函数接受一个时间间隔 `delay`,并返回一个装饰器函数。装饰器函数 `wrapper` 在每次调用被装饰的函数之前会检查距离上一次调用的时间间隔,如果小于 `delay`,则直接返回,否则执行被装饰的函数节流函数的作用是在指定的时间间隔内,保证函数执行的频率不超过指定的次数。常见的应用场景是在用户频繁触发事件(如滚动、鼠标移动等)时,进行性能优化。 一个简单节流函数可以这样实现: ```python import time def throttle(limit): def decorator(func): last_called = 0 count = 0 def wrapper(*args, **kwargs): nonlocal last_called, count now = time.time() if now - last_called > limit: count = 0 last_called = now count += 1 if count <= limit: return func(*args, **kwargs) return wrapper return decorator ``` 使用示例: ```python @throttle(2) def log(message): print(message) for i in range(5): log(i) time.sleep(0.5) ``` 上述代码中,`throttle` 函数接受一个次数限制 `limit`,并返回一个装饰器函数。装饰器函数 `wrapper` 在每次调用被装饰的函数之前会检查距离上一次调用的时间间隔和执行次数,如果时间间隔大于限制且执行次数不超过限制,则执行被装饰的函数。 总结:防抖函数适用于需要延迟执行并且只关心最后一次调用结果的场景,节流函数适用于需要控制函数执行频率的场景。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奇怪的农民

你打赏的是无话不说

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值