Debounce vs Throttle: what's the difference, and implement throttle
Task
You're given a debouncer. Explain how debounce differs from throttle, find the weak spots in the code, and write a Throttler.
final class Debouncer {
private let delay: TimeInterval
private let queue: DispatchQueue
private var workItem: DispatchWorkItem?
init(delay: TimeInterval, queue: DispatchQueue = .main) {
self.delay = delay
self.queue = queue
}
func run(_ action: @escaping () -> Void) {
workItem?.cancel()
let item = DispatchWorkItem(block: action)
workItem = item
queue.asyncAfter(deadline: .now() + delay, execute: item)
}
}
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep