Last active
December 12, 2022 15:37
-
-
Save ayaysir/5075ee06cce25df9a14fb17360ebd0cb to your computer and use it in GitHub Desktop.
Debounce & Throttle 1
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
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) | |
} | |
} |
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
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() {} | |
} |
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
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