Skip to content

Commit a77afcb

Browse files
authored
Delayed animation cancellation (#231)
1 parent 25c8faf commit a77afcb

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

Impedance Converter/Impedance Converter/SmoothAnimation.swift

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,26 @@ class SmoothAnimation {
66
private var animationTimer: Timer?
77
private var currentInterpolator: Double
88
private var updateAction: ((Double) -> Void)?
9+
private var delayWorkItem: DispatchWorkItem?
910

1011
init(initialValue: Double = 0) {
1112
self.currentInterpolator = initialValue
1213
}
1314

1415
func startAnimating(target: Double, totalAnimationTime: Double = 0.25, delay: TimeInterval = 0, updateAction: @escaping (Double) -> Void) {
1516

16-
// Invalidate existing timer before starting a new animation
17-
animationTimer?.invalidate()
17+
// Stop existing animation before starting a new one
18+
stopAnimating()
1819

1920
if SmoothAnimation.isAnimationDisabled {
2021
self.currentInterpolator = target
2122
updateAction(target)
2223
return
2324
}
2425

25-
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
26+
let workItem = DispatchWorkItem { [weak self] in
27+
guard let self = self else { return }
28+
2629
self.updateAction = updateAction
2730
self.animationTimer?.invalidate()
2831
let startValue = self.currentInterpolator
@@ -47,19 +50,20 @@ class SmoothAnimation {
4750
self.updateAction?(interpolatorValue)
4851
}
4952
}
53+
54+
self.delayWorkItem = workItem
55+
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: workItem)
5056
}
5157

5258
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()
5561
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)
6063
}
6164

6265
func stopAnimating() {
6366
animationTimer?.invalidate()
67+
delayWorkItem?.cancel()
6468
}
6569
}

0 commit comments

Comments
 (0)