Last active
November 12, 2020 20:46
-
-
Save calt/e0e25a82403bb39d9e46d7ccb07ce6e3 to your computer and use it in GitHub Desktop.
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 Dispatch | |
final class Debouncer { | |
private var currentWorkItem = DispatchWorkItem(block: {}) | |
private let interval: TimeInterval | |
private let queue: DispatchQueue | |
init(interval: TimeInterval, queue: DispatchQueue = .main) { | |
self.interval = interval | |
self.queue = queue | |
} | |
func run(action: @escaping () -> Void) { | |
currentWorkItem.cancel() | |
currentWorkItem = DispatchWorkItem(block: { action() }) | |
queue.asyncAfter(deadline: .now() + interval, execute: currentWorkItem) | |
} | |
func cancel() { | |
currentWorkItem.cancel() | |
} | |
deinit { | |
currentWorkItem.cancel() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment