Skip to content

Instantly share code, notes, and snippets.

@albertodebortoli
Forked from ShamylZakariya/debounce.swift
Last active March 4, 2018 16:00
Show Gist options
  • Save albertodebortoli/6c8380b729468ecdb710 to your computer and use it in GitHub Desktop.
Save albertodebortoli/6c8380b729468ecdb710 to your computer and use it in GitHub Desktop.
Simple Swift Debouncer
func debounce( delay:NSTimeInterval, #queue:dispatch_queue_t, action: (()->()) ) -> ()->() {
var lastFireTime:dispatch_time_t = 0
let dispatchDelay = Int64(delay * Double(NSEC_PER_SEC))
return {
lastFireTime = dispatch_time(DISPATCH_TIME_NOW,0)
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
dispatchDelay
),
queue) {
let now = dispatch_time(DISPATCH_TIME_NOW,0)
let when = dispatch_time(lastFireTime, dispatchDelay)
if now >= when {
action()
}
}
}
}
class Debouncer: NSObject {
let delay: TimeInterval
let queue: DispatchQueue
var lastFireTime: DispatchTime!
init(delay: TimeInterval, queue: DispatchQueue) {
self.delay = delay
self.queue = queue
}
func debounce(action: @escaping (() -> Void)) {
self.lastFireTime = DispatchTime.now()
self.queue.asyncAfter(deadline: DispatchTime.now() + self.delay) {
let now = DispatchTime.now()
let when = self.lastFireTime + self.delay
if now >= when {
action()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment