介绍
cj_debounce_throttle是仓颉实现的debounce和throttle库,用于将高频触发的事件限制在一定范围。
debounce:防抖工具,在一定时间内只执行一次函数。
throttle:节流工具,在高频触发的动作的一定时间内周期性执行
项目结构
.
├── CHANGELOG.md
├── LICENSE
├── README.md
├── cjlintignore.cfg
├── cjpm.lock
├── cjpm.toml
└── src
├── macros
│ ├── repeatermacro.cj Debounce和Throttle宏实现
│ └── util.cj 处理Tokens的工具类
├── main.cj
└── repeater
├── reapter.cj Repeater类实现debounce和throttle功能
├── types.cj 类型定义
└── util.cj 工具类
安装使用
在cjpm.toml中添加如下依赖后执行 cjpm update
[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}')
}
注意点
- 可以给任意函数添加@Debounce和@Throttle
- 如果是独立的函数,不同包调用的相同函数共享一个定时器
约束与限制
- 本项目在Mac上编译通过,没有使用特殊API,其他平台也都可用
- 项目编译器版本为 0.56.4。如您的编译器版本不一致,可以通过cjpm.toml修改
开源协议
Apache License Version 2.0
参与贡献
欢迎给我们提交PR,欢迎给我们提交Issue,欢迎参与任何形式的贡献。