Skip to content

Instantly share code, notes, and snippets.

@Ikloo
Last active March 24, 2020 12:24
Show Gist options
  • Save Ikloo/7cc4d22e4d0406047f57c75df667150f to your computer and use it in GitHub Desktop.
Save Ikloo/7cc4d22e4d0406047f57c75df667150f to your computer and use it in GitHub Desktop.
Deferred funcs calls for Swift
//
// Debouncer.swift
//
// Created by Kirill Budevich on 11/14/19.
// Copyright © 2019 KB. All rights reserved.
//
import Foundation
final public class Debouncer {
private weak var timer: Timer?
public var delay: Measurement<UnitDuration>
public init(delay: Measurement<UnitDuration>) {
self.delay = delay
}
public func debounce(block: @escaping () -> Void) {
timer?.invalidate()
let interval = delay.converted(to: .seconds).value
timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false, block: { _ in block() })
}
}
//
// Throttler.swift
//
// Created by Kirill Budevich on 11/14/19.
// Copyright © 2019 KB. All rights reserved.
//
import Foundation
final public class Throttler {
private let queue: DispatchQueue = DispatchQueue.global(qos: .background)
private var job: DispatchWorkItem = DispatchWorkItem(block: {})
private var previousRun: Date = Date.distantPast
public var maxInterval: Measurement<UnitDuration>
public init(maxInterval: Measurement<UnitDuration>) {
self.maxInterval = maxInterval
}
public func throttle(block: @escaping () -> Void) {
job.cancel()
job = DispatchWorkItem(){ [weak self] in
self?.previousRun = Date()
block()
}
let interval = maxInterval.converted(to: .seconds).value
let delay = Date().timeIntervalSince(previousRun) > interval ? 0 : interval
queue.asyncAfter(deadline: .now() + Double(delay), execute: job)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment