// 废话不多说,直接上代码,需要在api 9下运行 @Observed class Obj { name:string age:number address:string constructor(p1:string,p2:number,p3:string) { this.name = p1 this.age = p2 this.address = p3 } } // 防抖 在一段时间内函数被多次触发,防抖让函数在一段时间后最终只执行一次 function fd(fn: Function, delay: number) { let timer: any = null return function () { if (timer) clearTimeout(timer) timer = setTimeout(() => { fn.apply(this, arguments) }, delay) } } // 节流 函数被连续触发多少次,节流就是让函数按照特定的频率去执行 function jl(fn, delay) { let flag = true return function () { if (!flag) return flag = false setTimeout(() => { fn(this, arguments) flag = true }, delay) } } @Entry @Component struct parent { @State arr: Obj[] = [new Obj('张三', 18, '云南'), new Obj('李四', 20, '浙江')] // 防抖实现 testFD(item) { console.log('防抖',item) } debouncedTestFd=fd(this.testFD.bind(this),1000) // 节流实现 testJL(item) { console.log('节流',item) } throttleDTestJl = jl(this.testJL.bind(this),1000) build() { Column() { ForEach(this.arr, (item, index) => { Column() { Text('姓名:' + item.name) Divider().padding({ top: 10, bottom: 10 }).color('#ff870be0') Row() { Text('年龄:' + item.age) Blank() Button('change').fontColor('#ffd0c606').stateStyles({ pressed: { .backgroundColor(Color.Gray) }, normal: { .backgroundColor(Color.Brown) } }) // 防抖 // .onClick(this.debouncedTestFd) //不可用fd(this.testFD.bind(this),1000)替换this.debounceTestFd // 节流 .onClick(this.throttleDTestJl) //同理,不可使用jl(this.testJL.bind(this),1000)替换this.throttledTestJl }.width('100%') Divider().padding({ top: 10, bottom: 10 }).color('#ff870be0') Text('地址:' + item.address) } .border({ width: 1, color: '#ff34d5dd', radius: 8 }) .padding(15) .width('100%') .alignItems(HorizontalAlign.Start) .colorBlend('#ff676966') .margin({ top: 10 }) }) } } }