cj_debounce_throttle:基于仓颉的防抖节流工具库项目

仓颉实现的debounce和throttle库

Branch1Tags0
FilesLast commitLast update
5 months ago
5 months ago
5 months ago
5 months ago
2 years ago
5 months ago
2 years ago
2 years ago
5 months ago

介绍

cj_debounce_throttle是仓颉实现的debounce和throttle库,用于将高频触发的事件限制在一定范围。

debounce:防抖工具,在一定时间内只执行一次函数。

throttle:节流工具,在高频触发的动作的一定时间内周期性执行

项目结构

.
├── CHANGELOG.md
├── LICENSE
├── README_zh.md
├── cjlintignore.cfg
├── cjpm.lock
├── cjpm.toml
└── src
    ├── macros
    │   ├── repeatermacro.cj Debounce和Throttle宏实现
    │   └── util.cj 处理Tokens的工具类
    ├── cj_debounce_throttle.cj 根包聚合导出
    └── repeater
        ├── repeater.cj Repeater 类实现 debounce 与 throttle
        ├── types.cj 类型定义
        ├── types_test.cj 单元测试
        └── util.cj 工具类

发布到仓颉中心仓

发布前请确保本机 cjpm build 与 cjpm test 能通过(cjpm publish 会先执行 cjpm bundle,其中包含构建、测试与 cjlint)。若链接阶段报错(例如 libSystem.tbd ... incompatible with arm64),多为本机 Xcode / Command Line Tools 与仓颉自带链接器组合问题,请在可正常链接的环境中重试或按仓颉发行说明调整 SDK。

cjpm bundle    # 在 target 下生成可分发包(默认会跑测试与 cjlint)
cjpm publish   # 将当前版本上传到中心仓(需已配置中心仓账号/令牌,参见仓颉官方「包发布」文档)
[dependencies]
  cj_debounce_throttle = { git='https://gitcode.com/unravel/cj_debounce_throttle.git', output-type='static', branch='main' }

单独使用

导入

import cj_debounce_throttle.repeater.*

Debounce

let start = getNowTime()
let debouncer = Repeater(throttle: false, mode: Trailing(100)) {
    println('testDebounce执行间隔 ${getNowTime()-start}')
}

debouncer.call()

Throttle

let start = getNowTime()
let throttler = Repeater(throttle: true, mode: Trailing(50)) {
    println('testThrottle执行间隔 ${getNowTime()-start}')
}

借助宏使用

导入宏

import cj_debounce_throttle.macros.*

类的实例成员方法

class RepeaterMemberMacro {
    let start = getNowTime()

    @Debounce[100]
    func myDebounce() {
        println('myDebounce执行间隔 ${getNowTime()-start}')
    }

    @Throttle[50]
    func myThrottle() {
        println('myThrottle执行间隔 ${getNowTime()-start}')
    }
}

全局方法

let start = getNowTime()
@Debounce[100]
func debounceFunc() {
    println('myDebounce执行间隔 ${getNowTime()-start}')
}

@Throttle[50]
func throttleFunc() {
    println('myThrottle执行间隔 ${getNowTime()-start}')
}

注意点

  1. 可以给任意函数添加@Debounce和@Throttle
  2. 如果是独立的函数,不同包调用的相同函数共享一个定时器

约束与限制

  1. 本项目在Mac上编译通过,没有使用特殊API,其他平台也都可用
  2. 最低编译器版本以 cjpm.toml 中 cjc-version 为准(当前为 1.1.0)

开源协议

Apache License Version 2.0

参与贡献

欢迎给我们提交PR,欢迎给我们提交Issue,欢迎参与任何形式的贡献。

Introduction

仓颉实现的debounce和throttle库

Customize your domain