Created
March 19, 2015 17:32
-
-
Save mzaks/33e25c85454f96fae540 to your computer and use it in GitHub Desktop.
This file contains 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
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