Visual_Novel_iOS/crush/Crush/Src/Components/Audio/TimerModel.swift

56 lines
1.3 KiB
Swift
Raw Normal View History

2025-10-09 10:29:35 +00:00
//
// TimerModel.swift
// Crush
//
// Created by Leon on 2025/8/1.
//
import Foundation
class TimerModel {
// MARK: - Properties
private var timer: DispatchSourceTimer?
private var isSuspended: Bool = false
var timerBlock: (() -> Void)?
// MARK: - Lazy Timer
private func createTimer() -> DispatchSourceTimer {
let timer = DispatchSource.makeTimerSource(queue: .global())
timer.schedule(deadline: .now(), repeating: .milliseconds(100)) // 0.1s interval
timer.setEventHandler { [weak self] in
self?.timerBlock?()
}
return timer
}
// MARK: - Public Methods
func startTimer() {
if !isSuspended, timer != nil { return }
isSuspended = false
if timer == nil {
timer = createTimer()
}
timer?.resume()
//dlog("🔥: resume once")
}
func pauseTimer() {
guard let timer = timer, !isSuspended else { return }
isSuspended = true
timer.suspend()
//dlog("🔥: suspend once")
}
// MARK: - Deinit
deinit {
dlog("📻 audio timer dealloc")
if let timer = timer {
if isSuspended {
startTimer() // Resume to allow cancellation
}
timer.cancel()
self.timer = nil
}
}
}