Skip to content

Instantly share code, notes, and snippets.

@unixzii
Created December 8, 2016 07:07
Show Gist options
  • Save unixzii/2ead93805fd936ef92f2a738b67c0a92 to your computer and use it in GitHub Desktop.
Save unixzii/2ead93805fd936ef92f2a738b67c0a92 to your computer and use it in GitHub Desktop.
debounce 与 throttle 高阶函数简易实现以及演示两者区别
//: 理解 Debouncing 与 Throttling 的区别
import Cocoa
import PlaygroundSupport
typealias Action = () -> ()
func debounce(threshold: TimeInterval, action: @escaping Action) -> Action {
var timer: DispatchSourceTimer?
return {
if timer != nil {
timer!.cancel()
}
timer = DispatchSource.makeTimerSource()
timer!.setEventHandler {
action()
}
timer!.scheduleOneshot(deadline: .now() + .milliseconds(Int(threshold * 1000)))
timer!.activate()
}
}
func throttle(threshold: TimeInterval, action: @escaping Action) -> Action {
var last: CFAbsoluteTime = 0
return {
let current = CFAbsoluteTimeGetCurrent();
if current >= last + threshold {
action()
last = current
}
}
}
class TestCase {
let throttledFunc = throttle(threshold: 0.5) {
print("Throttle button clicked!")
}
let debouncedFunc = debounce(threshold: 0.5) {
print("Debounce button clicked!")
}
@objc func testThrottle() {
throttledFunc()
}
@objc func testDebounce() {
debouncedFunc()
}
}
let test = TestCase()
let throttleButton = NSButton.init(title: "Throttle", target: test, action: #selector(TestCase.testThrottle))
let debounceButton = NSButton.init(title: "Debounce", target: test, action: #selector(TestCase.testDebounce))
let view = NSStackView(views: [throttleButton, debounceButton])
view.orientation = .vertical
view.frame = NSMakeRect(0, 0, 100, 100)
PlaygroundPage.current.liveView = view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment