Skip to content

Commit aa59c01

Browse files
committed
Add ThrottleRunner
1 parent 22ac6af commit aa59c01

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Tool/Sources/DebounceFunction/ThrottleFunction.swift

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,40 @@ public actor ThrottleFunction<T> {
4040
}
4141
}
4242

43+
public actor ThrottleRunner {
44+
let duration: TimeInterval
45+
var lastFinishTime: Date = .init(timeIntervalSince1970: 0)
46+
var now: () -> Date = { Date() }
47+
var task: Task<Void, Error>?
48+
49+
public init(duration: TimeInterval) {
50+
self.duration = duration
51+
}
52+
53+
public func throttle(block: @escaping () async -> Void) {
54+
if task == nil {
55+
scheduleTask(wait: now().timeIntervalSince(lastFinishTime) < duration, block: block)
56+
}
57+
}
58+
59+
func scheduleTask(wait: Bool, block: @escaping () async -> Void) {
60+
task = Task.detached { [weak self] in
61+
guard let self else { return }
62+
do {
63+
if wait {
64+
try await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000))
65+
}
66+
await block()
67+
await finishTask()
68+
} catch {
69+
await finishTask()
70+
}
71+
}
72+
}
73+
74+
func finishTask() {
75+
task = nil
76+
lastFinishTime = now()
77+
}
78+
}
79+

0 commit comments

Comments
 (0)