Skip to content

Commit

Permalink
Delayed animation cancellation (#231)
Browse files Browse the repository at this point in the history
  • Loading branch information
mfikes authored May 5, 2024
1 parent 25c8faf commit a77afcb
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions Impedance Converter/Impedance Converter/SmoothAnimation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,26 @@ class SmoothAnimation {
private var animationTimer: Timer?
private var currentInterpolator: Double
private var updateAction: ((Double) -> Void)?
private var delayWorkItem: DispatchWorkItem?

init(initialValue: Double = 0) {
self.currentInterpolator = initialValue
}

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

// Invalidate existing timer before starting a new animation
animationTimer?.invalidate()
// Stop existing animation before starting a new one
stopAnimating()

if SmoothAnimation.isAnimationDisabled {
self.currentInterpolator = target
updateAction(target)
return
}

DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
let workItem = DispatchWorkItem { [weak self] in
guard let self = self else { return }

self.updateAction = updateAction
self.animationTimer?.invalidate()
let startValue = self.currentInterpolator
Expand All @@ -47,19 +50,20 @@ class SmoothAnimation {
self.updateAction?(interpolatorValue)
}
}

self.delayWorkItem = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: workItem)
}

func startAnimating(from: Double, target: Double, totalAnimationTime: Double = 0.25, delay: TimeInterval = 0, updateAction: @escaping (Double) -> Void) {
// Invalidate existing timer before starting a new animation
animationTimer?.invalidate()
// Stop existing animation before starting a new one
stopAnimating()
self.currentInterpolator = from

DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
self.startAnimating(target: target, totalAnimationTime: totalAnimationTime, updateAction: updateAction)
}
startAnimating(target: target, totalAnimationTime: totalAnimationTime, delay: delay, updateAction: updateAction)
}

func stopAnimating() {
animationTimer?.invalidate()
delayWorkItem?.cancel()
}
}

0 comments on commit a77afcb

Please sign in to comment.