Last active
September 1, 2023 21:44
-
-
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.
This file contains hidden or 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
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