Skip to content

Instantly share code, notes, and snippets.

@ayaysir
Last active December 12, 2022 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayaysir/5075ee06cce25df9a14fb17360ebd0cb to your computer and use it in GitHub Desktop.
Save ayaysir/5075ee06cce25df9a14fb17360ebd0cb to your computer and use it in GitHub Desktop.
Debounce & Throttle 1
import Foundation
class Debounce: DelayWork {
override func run() {
self.workItem?.cancel()
let workItem = DispatchWorkItem { [weak self] in
self?.handler?(Date())
}
self.workItem = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delay), execute: workItem)
}
}
import Foundation
class DelayWork {
typealias Handler = ((Date) -> Void)
var workItem: DispatchWorkItem?
let delay: Int!
let handler: Handler?
init(milliseconds delay: Int, handler: Handler?) {
self.delay = delay
self.handler = handler
}
func run() {}
}
import Foundation
class Throttle: DelayWork {
override func run() {
if self.workItem == nil {
handler?(Date())
let workItem = DispatchWorkItem { [weak self] in
self?.workItem?.cancel()
self?.workItem = nil
}
self.workItem = workItem
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delay), execute: workItem)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment