Skip to content

Instantly share code, notes, and snippets.

@NoemiRozpara
Created April 24, 2020 19:45
Show Gist options
  • Save NoemiRozpara/39366ad366c353959dda606fc17ae82d to your computer and use it in GitHub Desktop.
Save NoemiRozpara/39366ad366c353959dda606fc17ae82d to your computer and use it in GitHub Desktop.
Swift basic event throttling - not debouncing!
class Throttler {
private var currentTask: (() -> Void)?
private var timer: Timer?
private let minimumDelay: TimeInterval
init(minimumDelay: TimeInterval) {
self.minimumDelay = minimumDelay
}
func call(_ task: @escaping () -> Void) {
if(timer != nil) {
// if timer did not finish tick just get the most recent event
currentTask = task
} else {
// on tick execute and restart
task()
Timer.scheduledTimer(withTimeInterval: minimumDelay, repeats: false) { (t) in
self.currentTask?()
self.timer = nil
}
}
}
}
// Usage
let throttler = Throttler(minimumDelay: 1)
@IBAction func volumeSliderChanged(_ sender: UISlider) {
throttler.call {
self.updateVolume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment