Skip to content

Instantly share code, notes, and snippets.

@zakbarlow1995
Forked from bradfol/Debouncer.swift
Last active September 4, 2019 16:17
Show Gist options
  • Save zakbarlow1995/a592b0e898d46a5572e422077c0ae4d4 to your computer and use it in GitHub Desktop.
Save zakbarlow1995/a592b0e898d46a5572e422077c0ae4d4 to your computer and use it in GitHub Desktop.
import Foundation
class Debouncer {
/**
Create a new Debouncer instance with the provided time interval.
- parameter timeInterval: The time interval of the debounce window.
*/
init(timeInterval: TimeInterval) {
self.timeInterval = timeInterval
}
typealias Handler = () -> Void
/// Closure to be debounced.
/// Perform the work you would like to be debounced in this handler.
var handler: Handler?
/// Time interval of the debounce window.
private let timeInterval: TimeInterval
private var timer: Timer?
/// Indicate that the handler should be invoked.
/// Begins the debounce window with the duration of the time interval parameter.
/// - Parameter setHandlerToNil: Determines if handler closure is set to `nil` after execution. Defaults to `true`.
func renewInterval(setHandlerToNil: Bool = true) {
// Invalidate existing timer if there is one
timer?.invalidate()
// Begin a new timer from now
timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false, block: { [weak self] timer in
self?.handleTimer(timer, setHandlerToNil)
})
}
private func handleTimer(_ timer: Timer, _ setHandlerToNil: Bool) {
guard timer.isValid else {
return
}
handler?()
if setHandlerToNil {
handler = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment