-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathDebounceFunction.swift
More file actions
48 lines (37 loc) · 1.05 KB
/
DebounceFunction.swift
File metadata and controls
48 lines (37 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import Foundation
public actor DebounceFunction<T> {
let duration: TimeInterval
let block: (T) async -> Void
var task: Task<Void, Error>?
public init(duration: TimeInterval, block: @escaping (T) async -> Void) {
self.duration = duration
self.block = block
}
public func cancel() {
task?.cancel()
}
public func callAsFunction(_ t: T) async {
task?.cancel()
task = Task { [block, duration] in
try await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000))
await block(t)
}
}
}
public actor DebounceRunner {
let duration: TimeInterval
var task: Task<Void, Error>?
public init(duration: TimeInterval) {
self.duration = duration
}
public func cancel() {
task?.cancel()
}
public func debounce(_ block: @escaping () async -> Void) {
task?.cancel()
task = Task { [duration] in
try await Task.sleep(nanoseconds: UInt64(duration * 1_000_000_000))
await block()
}
}
}