Skip to content

Instantly share code, notes, and snippets.

@alemar11
Created June 16, 2020 10:27
Show Gist options
  • Save alemar11/c16779848f5040de99da41e92994389b to your computer and use it in GitHub Desktop.
Save alemar11/c16779848f5040de99da41e92994389b to your computer and use it in GitHub Desktop.
TypingThrottler
import Foundation
final class TypingThrottler {
typealias Handler = (String) -> Void
let interval: TimeInterval
let handler: Handler
private var workItem: DispatchWorkItem?
// handler will be called after the user has stopped typing for the given `interval` (seconds)
init(interval: TimeInterval = 0.4, handler: @escaping Handler) {
self.interval = interval
self.handler = handler
}
// call this every time the text changes
func handleTyping(with text: String) {
workItem?.cancel()
workItem = DispatchWorkItem { [weak self] in
self?.handler(text)
}
if let workItem = self.workItem {
DispatchQueue.main.asyncAfter(deadline: .now() + interval, execute: workItem)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment