Skip to content

Instantly share code, notes, and snippets.

@ShamylZakariya
Created September 4, 2014 21:01
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ShamylZakariya/54ee03228d955f458389 to your computer and use it in GitHub Desktop.
Save ShamylZakariya/54ee03228d955f458389 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()
}
}
}
}
@magnusstubman
Copy link

nice!

@parris
Copy link

parris commented Nov 25, 2014

@ShamylZakariya would you mind showing an example of how this works? (sorry, iOS beginner here)

@crodriguez1a
Copy link

@parris Something like...

let debounced = debounce(
    NSTimeInterval(0.25),
    queue: dispatch_get_main_queue(),
    {
      _ in
        //do work
    }
  )

@sebirkli
Copy link

sebirkli commented Feb 9, 2015

Can someone pls explain how to cancel methods? I'm implementing Search as you type and a request shall only be sent if a user hasn't type for more than 1 second.
I tried this solution and set delay for 5 sec and if I type 3 letters in 2 seconds, i have still 3 requests (at the moment i send after each typed letter a request), but i just want to have one request.
There should be a way to "restart" the function. Thanks in advance.

@anoop4real
Copy link

do you have a sample implementation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment