How can I debounce a method call?

前端 未结 13 1580
醉梦人生
醉梦人生 2020-11-30 01:18

I\'m trying to use a UISearchView to query google places. In doing so, on text change calls for my UISearchBar, I\'m making a request to google pla

13条回答
  •  心在旅途
    2020-11-30 02:00

    Here is a debounce implementation for Swift 3.

    https://gist.github.com/bradfol/541c010a6540404eca0f4a5da009c761

    import Foundation
    
    class Debouncer {
    
        // Callback to be debounced
        // Perform the work you would like to be debounced in this callback.
        var callback: (() -> Void)?
    
        private let interval: TimeInterval // Time interval of the debounce window
    
        init(interval: TimeInterval) {
            self.interval = interval
        }
    
        private var timer: Timer?
    
        // Indicate that the callback should be called. Begins the debounce window.
        func call() {
            // Invalidate existing timer if there is one
            timer?.invalidate()
            // Begin a new timer from now
            timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(handleTimer), userInfo: nil, repeats: false)
        }
    
        @objc private func handleTimer(_ timer: Timer) {
            if callback == nil {
                NSLog("Debouncer timer fired, but callback was nil")
            } else {
                NSLog("Debouncer timer fired")
            }
            callback?()
            callback = nil
        }
    
    }
    

提交回复
热议问题