Skip to content

Instantly share code, notes, and snippets.

@mzaks
Created March 19, 2015 17:32
Show Gist options
  • Save mzaks/33e25c85454f96fae540 to your computer and use it in GitHub Desktop.
Save mzaks/33e25c85454f96fae540 to your computer and use it in GitHub Desktop.
import Foundation
public typealias Action = ()->Void
/**
Bounced action takes interval and action to return another action, which limits the rate at which provided action can be fired.
It is like a bouncer at a discotheque. He will act on your questions only after you shut up for 'interval' of time.
This technique is important if you have action wich should fire on update, however the updates coming in to frequently sometimes.
Inspired by debounce function from underscore.js ( http://underscorejs.org )
*/
public func bouncedAction(interval : NSTimeInterval, action : Action) -> Action {
let bouncer = Bouncer(interval: interval, action: action)
return {
bouncer.update()
}
}
@objc internal class Bouncer {
var timer : NSTimer?
let action : Action
let interval : NSTimeInterval
private init(interval : NSTimeInterval, action : Action){
self.action = action
self.interval = interval
}
func update(){
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "execute", userInfo: nil, repeats: false)
}
func execute(){
action()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment