IOS/Swift延迟执行(去抖动debounce)

2020-12-22 271点热度 0人点赞 0条评论

IOS开发搜索功能,需要监听输入框,用户实时输入便启动请求后台搜索结果,但是用户快速输入每一个单词,就触发一次服务器请求,有点浪费资源,且体验不好,做法是等待用户比如500ms后,再进行搜索请求,以下是Swift代码:

新建Debouncer.swift
import Foundation

class Debouncer: NSObject {
    var callback: (() -> ())
    var delay: Double
    weak var timer: Timer?

    init(delay: Double, callback: @escaping (() -> ())) {
        self.delay = delay
        self.callback = callback
    }

    func call() {
        timer?.invalidate()
        let nextTimer = Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(Debouncer.fireNow), userInfo: nil, repeats: false)
        timer = nextTimer
    }

    @objc func fireNow() {
        self.callback()
    }
}
如何调用
let debouncedFunction = Debouncer(delay: 0.50) {
  //hell load http request
  print("delayed printing")
}

@IBAction func searchChanged(_ sender: Any) {
  debouncedFunction.call()
}

Java语言通用版本,请看https://blog.terrynow.com/2020/12/21/java-debounce/

Android版本,请看https://blog.terrynow.com/2020/12/22/android-debounce/

Javascript版本,请看https://blog.terrynow.com/2020/12/23/javascript-debounce/

admin

这个人很懒,什么都没留下

文章评论

*

code