Skip to content

Instantly share code, notes, and snippets.

@lipka
Last active September 1, 2023 21:44
Show Gist options
  • Save lipka/9f2d4547818625495d7cab994abac245 to your computer and use it in GitHub Desktop.
Save lipka/9f2d4547818625495d7cab994abac245 to your computer and use it in GitHub Desktop.
Limits the rate at which a closure is executed by preventing it's execution until a specified amount of time has elapsed.
import Foundation
/**
Limits the rate at which a closure is executed by preventing it's execution until a specified amount of time has elapsed.
Example:
```
let fetchThrottle = Throttle(interval: 60)
fetchThrottle {
// doExpensiveOperation()
}
```
*/
public class Throttle {
public let interval: TimeInterval
private var lastExecutionDate: Date?
public init(interval: TimeInterval) {
self.interval = interval
}
public func callAsFunction(_ operation: @escaping () -> Void) {
let now = Date()
if let lastExecutionDate, now.timeIntervalSince(lastExecutionDate) < interval {
return
}
lastExecutionDate = now
operation()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment