防抖函数,节流函数

防抖函数的作用是在短时间内频繁触发的事件只执行一次,节流函数的作用是在连续触发的事件中间隔一段时间执行一次。

以下是防抖函数和节流函数的示例代码:

防抖函数:

import time

def debounce(func, wait):
    timer = None
    
    def wrapper(*args, **kwargs):
        nonlocal timer
        
        if timer:
            clearTimeout(timer)
        
        timer = setTimeout(func, wait, *args, **kwargs)
    
    return wrapper

节流函数:

import time

def throttle(func, wait):
    last_executed_time = 0
    
    def wrapper(*args, **kwargs):
        nonlocal last_executed_time
        
        current_time = time.time()
        
        if current_time - last_executed_time > wait:
            func(*args, **kwargs)
            last_executed_time = current_time
    
    return wrapper

注意,以上代码是用Python语言来实现的,并参考了JavaScript中的setTimeout和clearTimeout函数的概念。在实际使用中,需要根据具体的编程环境来调整代码。

相关推荐

  1. 函数,节流函数

    2024-01-30 17:34:05       66 阅读
  2. 手写节流函数

    2024-01-30 17:34:05       28 阅读
  3. vue封装全局的节流函数

    2024-01-30 17:34:05       32 阅读
  4. vue 函数

    2024-01-30 17:34:05       46 阅读
  5. 函数为什么要

    2024-01-30 17:34:05       27 阅读
  6. lodash库(节流

    2024-01-30 17:34:05       35 阅读
  7. vue中使用lodash的debounce函数

    2024-01-30 17:34:05       60 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-30 17:34:05       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-30 17:34:05       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-30 17:34:05       82 阅读
  4. Python语言-面向对象

    2024-01-30 17:34:05       91 阅读

热门阅读

  1. 数据结构——队列链式存储实现

    2024-01-30 17:34:05       70 阅读
  2. TextCNN的复现

    2024-01-30 17:34:05       57 阅读
  3. SHELL编程-Linux自动化运维基础(循环与数组)

    2024-01-30 17:34:05       46 阅读
  4. Vue学习笔记之侦听器

    2024-01-30 17:34:05       67 阅读
  5. 【力扣经典面试题】27. 移除元素

    2024-01-30 17:34:05       64 阅读
  6. Spring JPA与Hibernate学习使用

    2024-01-30 17:34:05       60 阅读
  7. Oracle Extractor 软件下载

    2024-01-30 17:34:05       68 阅读
  8. git由SSH更改为HTTPS

    2024-01-30 17:34:05       51 阅读
  9. CSS transition(过渡效果)详解

    2024-01-30 17:34:05       52 阅读