Skip to content

Instantly share code, notes, and snippets.

@zvonicek
Last active October 28, 2017 09:49
Show Gist options
  • Save zvonicek/bf5e420f11c8ebe2c80d4a17ac322719 to your computer and use it in GitHub Desktop.
Save zvonicek/bf5e420f11c8ebe2c80d4a17ac322719 to your computer and use it in GitHub Desktop.
Will throttle the execution to once in every `delay` seconds.
func throttle<A>(delay:Int, queue:DispatchQueue, action: @escaping ((A)->())) -> (A)->() {
var lastFireTime = DispatchTime.now()
let dispatchDelay = DispatchTimeInterval.milliseconds(delay)
return { state in
let dispatchTime: DispatchTime = DispatchTime.now() + dispatchDelay
queue.asyncAfter(deadline: dispatchTime, execute: {
let when: DispatchTime = lastFireTime + dispatchDelay
let now = DispatchTime.now()
if now.rawValue >= when.rawValue {
lastFireTime = DispatchTime.now()
action(state)
}
})
}
}
@zvonicek
Copy link
Author

Example:

let throttledPrint: (String) -> () = throttle(delay: 1000, queue: DispatchQueue.main) { text in
    print(text)
}

// ...

throttledPrint("hello")

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