Last active
March 24, 2020 12:24
-
-
Save Ikloo/7cc4d22e4d0406047f57c75df667150f to your computer and use it in GitHub Desktop.
Deferred funcs calls for Swift
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
// | |
// 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() }) | |
} | |
} |
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
// | |
// 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