Created
April 24, 2020 19:45
-
-
Save NoemiRozpara/39366ad366c353959dda606fc17ae82d to your computer and use it in GitHub Desktop.
Swift basic event throttling - not debouncing!
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
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