File tree Expand file tree Collapse file tree
Tool/Sources/DebounceFunction Expand file tree Collapse file tree Original file line number Diff line number Diff 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+
You can’t perform that action at this time.
0 commit comments