Created
June 23, 2017 15:48
-
-
Save daehn/414212e1b4b30a43d995e4b5a4c2dad7 to your computer and use it in GitHub Desktop.
No more `performSelector:afterDelay` and `NSObject.cancelPreviousPerformRequests` in Swift.
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
class Throttle { | |
let delay: TimeInterval | |
private var workItem: DispatchWorkItem? | |
private let queue: DispatchQueue | |
init(delay: TimeInterval, queue: DispatchQueue = .main) { | |
self.delay = delay | |
self.queue = queue | |
} | |
func call(_ block: @escaping () -> Void) { | |
workItem?.cancel() | |
let item = DispatchWorkItem(block: block) | |
workItem = item | |
queue.asyncAfter(deadline: .now() + delay, execute: item) | |
} | |
} |
No issue with using it, but it only works with @objc
/ dynamic dispatch functions.
oh. thanks for the info.
It's a bit better to use DispatchTimeInterval
instead of TimeInterval
:
let delay: DispatchTimeInterval
Then you can instantiate it with:
Throttle(delay: .microseconds(10))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is there any issue when using
performSelector:afterDelay
withNSObject.cancelPreviousPerformRequests
?