prank/Funny_sounds/Tool/Timer.swift
2024-09-03 09:38:34 +08:00

45 lines
1.2 KiB
Swift

//
// 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
}
}