/
AKPlaygroundLoop.swift
47 lines (42 loc) · 1.33 KB
/
AKPlaygroundLoop.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//
// AKPlaygroundLoop.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2018 AudioKit. All rights reserved.
//
/// Class to handle updating via CADisplayLink
public class AKPlaygroundLoop: NSObject {
private var internalHandler: () -> Void = {}
private var duration = 1.0
/// Repeat this loop at a given period with a code block
///
/// - parameter every: Period, or interval between block executions
/// - parameter handler: Code block to execute
///
@objc public init(every dur: Double, handler: @escaping () -> Void) {
duration = dur
internalHandler = handler
super.init()
update()
}
/// Repeat this loop at a given frequency with a code block
///
/// - parameter frequency: Frequency of block executions in Hz
/// - parameter handler: Code block to execute
///
@objc public init(frequency: Double, handler: @escaping () -> Void) {
duration = 1.0 / frequency
internalHandler = handler
super.init()
update()
}
/// Callback function
@objc func update() {
self.internalHandler()
self.perform(#selector(update),
with: nil,
afterDelay: duration,
inModes: [RunLoop.Mode.common])
}
}