Created
January 21, 2016 19:26
-
-
Save rnapier/a1df22bb322f57f3f7a2 to your computer and use it in GitHub Desktop.
Untested port of RNTimer to 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
// Totally untested version of https://github.com/rnapier/RNTimer | |
import Foundation | |
final class RepeatingTimer { | |
var block: () -> Void | |
let source: dispatch_source_t | |
init(timeInterval: NSTimeInterval, block: () -> Void) { | |
assert(timeInterval != 0) | |
self.block = block; | |
source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, | |
0, 0, | |
dispatch_get_main_queue()) | |
let nsec = UInt64(timeInterval) * NSEC_PER_SEC | |
dispatch_source_set_timer(source, | |
dispatch_time(DISPATCH_TIME_NOW, Int64(nsec)), | |
nsec, 0) | |
dispatch_source_set_event_handler(source, block); | |
dispatch_resume(source); | |
} | |
deinit { | |
invalidate() | |
} | |
func invalidate() { | |
dispatch_source_cancel(source) | |
block = {} | |
} | |
func fire() { | |
block() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment