Last active
September 28, 2020 14:52
-
-
Save bradfol/541c010a6540404eca0f4a5da009c761 to your computer and use it in GitHub Desktop.
Debouncer Class Swift 4 – https://bradfol.com/how-can-i-debounce-a-method-call-in-swift-4/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
func renewInterval() { | |
// 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) | |
}) | |
} | |
private func handleTimer(_ timer: Timer) { | |
guard timer.isValid else { | |
return | |
} | |
handler?() | |
handler = nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment