mirror of
https://github.com/yattee/yattee.git
synced 2025-08-09 20:24:06 +00:00
Add to playlist from video player, state fixes
This commit is contained in:
40
Shared/Throttle.swift
Normal file
40
Shared/Throttle.swift
Normal file
@@ -0,0 +1,40 @@
|
||||
import Foundation
|
||||
|
||||
final class Throttle {
|
||||
let interval: TimeInterval
|
||||
private(set) var lastExecutedAt: Date?
|
||||
|
||||
private let syncQueue = DispatchQueue(label: "net.yatee.app.throttle")
|
||||
|
||||
init(interval: TimeInterval) {
|
||||
self.interval = interval
|
||||
}
|
||||
|
||||
@discardableResult func execute(_ action: () -> Void) -> Bool {
|
||||
let executed = syncQueue.sync { () -> Bool in
|
||||
let now = Date()
|
||||
|
||||
let timeInterval = now.timeIntervalSince(lastExecutedAt ?? .distantPast)
|
||||
|
||||
if timeInterval > interval {
|
||||
lastExecutedAt = now
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
if executed {
|
||||
action()
|
||||
}
|
||||
|
||||
return executed
|
||||
}
|
||||
|
||||
func reset() {
|
||||
syncQueue.sync {
|
||||
lastExecutedAt = nil
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user