Skip to content

Instantly share code, notes, and snippets.

@ha1f
Last active January 24, 2019 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ha1f/4bc7a78bbd19a756319884e132b7e7e8 to your computer and use it in GitHub Desktop.
Save ha1f/4bc7a78bbd19a756319884e132b7e7e8 to your computer and use it in GitHub Desktop.
import Foundation
/// Debouncer is useful for situations like following.
/// If we want to execute action n sec after the last trigger.
public final class Debouncer<T> {
let dispatchQueue: DispatchQueue
let interval: TimeInterval
let action: (T) -> Void
private var _lastDispatchTime: DispatchTime?
public init(_ dispatchQueue: DispatchQueue, interval: TimeInterval, action: @escaping (T) -> Void) {
self.dispatchQueue = dispatchQueue
self.interval = interval
self.action = action
}
/// Request action to execute.
public func requestAction(_ dependency: T) {
let dispatchTime: DispatchTime = .now() + interval
_lastDispatchTime = dispatchTime
dispatchQueue.asyncAfter(deadline: dispatchTime) {
guard self._lastDispatchTime == dispatchTime else {
// ignore if requested again during interval.
return
}
self.action(dependency)
}
}
}
extension Debouncer where T == Void {
public func requestAction() {
requestAction(())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment