当前位置: 首页 > news >正文

当滑动组件连续触发回调函数的三种解决办法

1. 节流(Throttle)

节流是一种限制函数调用频率的技术,它会在一定时间内只允许函数执行一次。在滑动组件中使用节流可以避免短时间内的连续触发。

@Entry
@Component
struct ThrottleSlideExample {
    // 节流时间间隔,单位为毫秒
    private throttleInterval: number = 500;
    // 上次执行滑动处理的时间
    private lastExecuteTime: number = 0;

    build() {
        Column({ space: 50 }) {
            List({ space: 10 }) {
                ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], (item) => {
                    ListItem() {
                        Text(`Item ${item}`)
                          .fontSize(20)
                          .padding(20)
                          .backgroundColor('#EEEEEE')
                    }
                })
            }
           .onScroll((event: ScrollEvent) => {
                const currentTime = Date.now();
                if (currentTime - this.lastExecuteTime > this.throttleInterval) {
                    // 超过节流时间间隔,执行滑动处理
                    console.log('执行滑动处理');
                    this.lastExecuteTime = currentTime;
                }
            })
        }
       .width('100%')
    }
}

代码解释

  • throttleInterval:定义节流的时间间隔,这里设置为 500 毫秒。
  • lastExecuteTime:记录上次执行滑动处理的时间。
  • 在 onScroll 事件中,获取当前时间 currentTime,判断当前时间与上次执行时间的差值是否超过节流时间间隔。如果超过,则执行滑动处理并更新 lastExecuteTime

2. 防抖(Debounce)

防抖是指在一定时间内,如果函数被多次调用,只执行最后一次调用。在滑动组件中使用防抖可以避免连续触发带来的问题。

@Entry
@Component
struct DebounceSlideExample {
    // 防抖时间间隔,单位为毫秒
    private debounceInterval: number = 300;
    // 定时器 ID
    private timer: number | null = null;

    build() {
        Column({ space: 50 }) {
            List({ space: 10 }) {
                ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], (item) => {
                    ListItem() {
                        Text(`Item ${item}`)
                          .fontSize(20)
                          .padding(20)
                          .backgroundColor('#EEEEEE')
                    }
                })
            }
           .onScroll((event: ScrollEvent) => {
                if (this.timer) {
                    // 如果定时器存在,清除定时器
                    clearTimeout(this.timer);
                }
                this.timer = setTimeout(() => {
                    // 经过防抖时间间隔后执行滑动处理
                    console.log('执行滑动处理');
                    this.timer = null;
                }, this.debounceInterval);
            })
        }
       .width('100%')
    }
}

代码解释

  • debounceInterval:定义防抖的时间间隔,这里设置为 300 毫秒。
  • timer:用于存储定时器的 ID。
  • 在 onScroll 事件中,如果定时器存在,则清除定时器。然后重新设置一个定时器,在经过防抖时间间隔后执行滑动处理。

3. 状态标记

使用状态标记来记录是否已经处理过一定次数的触发,当达到指定次数后,设置标记为已处理,直到满足特定条件(如一段时间后)再重置标记。

@Entry
@Component
struct FlagSlideExample {
    // 记录滑动触发次数
    private slideCount: number = 0;
    // 允许的最大触发次数
    private maxCount: number = 3;
    // 处理标记
    private isHandled: boolean = false;

    build() {
        Column({ space: 50 }) {
            List({ space: 10 }) {
                ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], (item) => {
                    ListItem() {
                        Text(`Item ${item}`)
                          .fontSize(20)
                          .padding(20)
                          .backgroundColor('#EEEEEE')
                    }
                })
            }
           .onScroll((event: ScrollEvent) => {
                if (!this.isHandled) {
                    this.slideCount++;
                    if (this.slideCount >= this.maxCount) {
                        // 达到最大触发次数,进行处理
                        console.log('执行滑动处理');
                        this.isHandled = true;
                        // 一段时间后重置标记
                        setTimeout(() => {
                            this.isHandled = false;
                            this.slideCount = 0;
                        }, 2000);
                    }
                }
            })
        }
       .width('100%')
    }
}

代码解释

  • slideCount:记录滑动触发次数。
  • maxCount:允许的最大触发次数,这里设置为 3 次。
  • isHandled:处理标记,用于记录是否已经处理过最大触发次数。
  • 在 onScroll 事件中,如果标记为未处理,则增加触发次数。当达到最大触发次数时,执行滑动处理并设置标记为已处理。然后使用 setTimeout 在 2000 毫秒(即 2 秒)后重置标记和触发次数。

这些方法各有优缺点,你可以根据具体的业务需求选择合适的方法来处理滑动组件连续触发的问题。


文章转载自:

http://XFSi2Tgo.fsqbx.cn
http://AmMbAWY8.fsqbx.cn
http://xc5qtj4z.fsqbx.cn
http://yAfEVKfB.fsqbx.cn
http://yf1UXrTa.fsqbx.cn
http://0pO7havn.fsqbx.cn
http://G3Z654IH.fsqbx.cn
http://yZ5bOudY.fsqbx.cn
http://nOFitkt6.fsqbx.cn
http://VckFLRmW.fsqbx.cn
http://IwUzNAxO.fsqbx.cn
http://psIPU0YW.fsqbx.cn
http://seTQbtbV.fsqbx.cn
http://pMBzgIaR.fsqbx.cn
http://lCY9rFh5.fsqbx.cn
http://0sCLAiUk.fsqbx.cn
http://fwlVH3sk.fsqbx.cn
http://AGnJBnlC.fsqbx.cn
http://U9dokm87.fsqbx.cn
http://LpbZUTj2.fsqbx.cn
http://qPZi8LlY.fsqbx.cn
http://wSdim99B.fsqbx.cn
http://G5OtMdo9.fsqbx.cn
http://eihpjx7r.fsqbx.cn
http://qMcLcU3S.fsqbx.cn
http://z9iZHTXS.fsqbx.cn
http://nx87hjBK.fsqbx.cn
http://gqhsAAWW.fsqbx.cn
http://LB54V43P.fsqbx.cn
http://hgRptjdn.fsqbx.cn
http://www.dtcms.com/a/28556.html

相关文章:

  • 回调处理器
  • Qt程序退出相关资源释放问题
  • MySQL基础回顾#1
  • jQuery UI CSS 框架 API
  • PyTorch 系统教程:PyTorch 入门项目(简单线性回归)
  • 使用代码与 AnythingLLM 交互的基本方法和示例
  • 30天开发操作系统 第22天 -- 用C语言编写应用程序
  • 模型训练与优化遇到的问题3:安装STM32Cube.AI
  • Webpack的持久化缓存机制具体是如何实现的?
  • 【鸿蒙笔记-基础篇_状态管理】
  • scrapy pipelines过滤重复数据
  • Nginx WebSocket 长连接及数据容量配置
  • 文献阅读 250220-Convective potential and fuel availability complement near-surface
  • 10个Python 语法错误(SyntaxError)常见例子及解决方案
  • 2016年下半年软件设计师上午题的知识点总结(附真题及答案解析)
  • 后端Java Stream数据流的使用=>代替for循环
  • 接口测试-API测试中常用的协议(中)
  • 解锁机器学习核心算法|神经网络:AI 领域的 “超级引擎”
  • 本地在ollama上部署deepseek或llama大模型
  • 2024华为OD机试真题-恢复数字序列(C++/Java/Python)-E卷-100分
  • Vue 中组件通信的方式有哪些,如何实现父子组件和非父子组件之间的通信?
  • 【含文档+PPT+源码】基于大数据的交通流量预测系统
  • 解决本地模拟IP的DHCP冲突问题
  • NutUI内网离线部署
  • 20250218反函数求导
  • IPv6报头40字节具体怎么分配的?
  • 快速入门Springboot+vue——MybatisPlus快速上手
  • 16 中介者(Mediator)模式
  • 编写测试计划的六大要素是什么
  • Python网络爬虫技术详解文档