Skip to content

Instantly share code, notes, and snippets.

@daehn
Created June 23, 2017 15:48
Show Gist options
  • Select an option

  • Save daehn/414212e1b4b30a43d995e4b5a4c2dad7 to your computer and use it in GitHub Desktop.

Select an option

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)
}
}
@RobinDaugherty

RobinDaugherty commented Apr 19, 2022

Copy link
Copy Markdown

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