@@ -6,23 +6,26 @@ class SmoothAnimation {
6
6
private var animationTimer : Timer ?
7
7
private var currentInterpolator : Double
8
8
private var updateAction : ( ( Double ) -> Void ) ?
9
+ private var delayWorkItem : DispatchWorkItem ?
9
10
10
11
init ( initialValue: Double = 0 ) {
11
12
self . currentInterpolator = initialValue
12
13
}
13
14
14
15
func startAnimating( target: Double , totalAnimationTime: Double = 0.25 , delay: TimeInterval = 0 , updateAction: @escaping ( Double ) -> Void ) {
15
16
16
- // Invalidate existing timer before starting a new animation
17
- animationTimer ? . invalidate ( )
17
+ // Stop existing animation before starting a new one
18
+ stopAnimating ( )
18
19
19
20
if SmoothAnimation . isAnimationDisabled {
20
21
self . currentInterpolator = target
21
22
updateAction ( target)
22
23
return
23
24
}
24
25
25
- DispatchQueue . main. asyncAfter ( deadline: . now( ) + delay) {
26
+ let workItem = DispatchWorkItem { [ weak self] in
27
+ guard let self = self else { return }
28
+
26
29
self . updateAction = updateAction
27
30
self . animationTimer? . invalidate ( )
28
31
let startValue = self . currentInterpolator
@@ -47,19 +50,20 @@ class SmoothAnimation {
47
50
self . updateAction ? ( interpolatorValue)
48
51
}
49
52
}
53
+
54
+ self . delayWorkItem = workItem
55
+ DispatchQueue . main. asyncAfter ( deadline: . now( ) + delay, execute: workItem)
50
56
}
51
57
52
58
func startAnimating( from: Double , target: Double , totalAnimationTime: Double = 0.25 , delay: TimeInterval = 0 , updateAction: @escaping ( Double ) -> Void ) {
53
- // Invalidate existing timer before starting a new animation
54
- animationTimer ? . invalidate ( )
59
+ // Stop existing animation before starting a new one
60
+ stopAnimating ( )
55
61
self . currentInterpolator = from
56
-
57
- DispatchQueue . main. asyncAfter ( deadline: . now( ) + delay) {
58
- self . startAnimating ( target: target, totalAnimationTime: totalAnimationTime, updateAction: updateAction)
59
- }
62
+ startAnimating ( target: target, totalAnimationTime: totalAnimationTime, delay: delay, updateAction: updateAction)
60
63
}
61
64
62
65
func stopAnimating( ) {
63
66
animationTimer? . invalidate ( )
67
+ delayWorkItem? . cancel ( )
64
68
}
65
69
}
0 commit comments