-
Notifications
You must be signed in to change notification settings - Fork 58
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
7997696
commit 1f05406
Showing
2 changed files
with
62 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
// | ||
// Timings.swift | ||
// rem | ||
// | ||
// Created by Jason McGhee on 12/30/23. | ||
// | ||
|
||
import Foundation | ||
|
||
class Debouncer { | ||
private var lastFireTime: DispatchTime = .now() | ||
private var delay: TimeInterval | ||
private var workItem: DispatchWorkItem? | ||
|
||
init(delay: TimeInterval) { | ||
self.delay = delay | ||
} | ||
|
||
func debounce(action: @escaping () -> Void) { | ||
workItem?.cancel() | ||
workItem = DispatchWorkItem { action() } | ||
let deadline = lastFireTime + delay | ||
DispatchQueue.main.asyncAfter(deadline: deadline, execute: workItem!) | ||
lastFireTime = deadline | ||
} | ||
} | ||
|
||
class Throttler { | ||
private var lastExecution: Date = Date.distantPast | ||
private let delay: TimeInterval | ||
private var workItem: DispatchWorkItem? | ||
private let queue: DispatchQueue | ||
|
||
init(delay: TimeInterval, queue: DispatchQueue = DispatchQueue.main) { | ||
self.delay = delay | ||
self.queue = queue | ||
} | ||
|
||
func throttle(_ block: @escaping () -> Void) { | ||
workItem?.cancel() | ||
|
||
let now = Date() | ||
let deadline = lastExecution.addingTimeInterval(delay) | ||
if now >= deadline { | ||
lastExecution = now | ||
block() | ||
} else { | ||
workItem = DispatchWorkItem { | ||
self.lastExecution = Date() | ||
block() | ||
} | ||
let dispatchDelay = DispatchTimeInterval.milliseconds(Int((deadline.timeIntervalSince(now)) * 1000)) | ||
queue.asyncAfter(deadline: .now() + dispatchDelay, execute: workItem!) | ||
} | ||
} | ||
} |