Skip to content

Instantly share code, notes, and snippets.

@daehn
Created June 23, 2017 15:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daehn/414212e1b4b30a43d995e4b5a4c2dad7 to your computer and use it in GitHub Desktop.
Save daehn/414212e1b4b30a43d995e4b5a4c2dad7 to your computer and use it in GitHub Desktop.
No more `performSelector:afterDelay` and `NSObject.cancelPreviousPerformRequests` in Swift.
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)
}
}
@lalkrishna
Copy link

is there any issue when using performSelector:afterDelaywith NSObject.cancelPreviousPerformRequests ?

@daehn
Copy link
Author

daehn commented Aug 31, 2021

No issue with using it, but it only works with @objc / dynamic dispatch functions.

@lalkrishna
Copy link

oh. thanks for the info.

@RobinDaugherty
Copy link

RobinDaugherty commented Apr 19, 2022

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