]>
Commit | Line | Data |
---|---|---|
1 | import Foundation | |
2 | ||
3 | class Debouncer { | |
4 | ||
5 | // MARK: - Properties | |
6 | private let queue = DispatchQueue.main | |
7 | private var workItem = DispatchWorkItem(block: {}) | |
8 | private var interval: TimeInterval | |
9 | ||
10 | // MARK: - Initializer | |
11 | init(seconds: TimeInterval) { | |
12 | self.interval = seconds | |
13 | } | |
14 | ||
15 | // MARK: - Debouncing function | |
16 | func debounce(action: @escaping (() -> Void)) { | |
17 | workItem.cancel() | |
18 | workItem = DispatchWorkItem(block: { action() }) | |
19 | queue.asyncAfter(deadline: .now() + interval, execute: workItem) | |
20 | } | |
21 | } |