Created
September 4, 2014 21:01
-
-
Save ShamylZakariya/54ee03228d955f458389 to your computer and use it in GitHub Desktop.
Simple Swift Debouncer
This file contains hidden or 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
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() | |
} | |
} | |
} | |
} |
@ShamylZakariya would you mind showing an example of how this works? (sorry, iOS beginner here)
@parris Something like...
let debounced = debounce(
NSTimeInterval(0.25),
queue: dispatch_get_main_queue(),
{
_ in
//do work
}
)
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.
do you have a sample implementation?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice!