// // Timeer.swift // Funny_sounds // // Created by 忆海16 on 2024/8/16. // import Foundation class CountdownTimer { private var timer: Timer? private var remainingSeconds: Int private var onTick: ((Int) -> Void)? private var onComplete: (() -> Void)? init(seconds: Int, onTick: @escaping (Int) -> Void, onComplete: @escaping () -> Void) { self.remainingSeconds = seconds self.onTick = onTick self.onComplete = onComplete } func start() { timer?.invalidate() // 确保没有其他计时器在运行 onTick?(remainingSeconds) // 立即触发一次 timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in guard let self = self else { return } self.remainingSeconds -= 1 self.onTick?(self.remainingSeconds) if self.remainingSeconds <= 0 { self.timer?.invalidate() self.onComplete?() } } } func stop() { timer?.invalidate() } func reset(with seconds: Int) { stop() remainingSeconds = seconds } }