Skip to content

Instantly share code, notes, and snippets.

@ataias
Forked from natecook1000/NSTimer+Closure.swift
Created February 10, 2016 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ataias/0a3239e5ac07ba1e0767 to your computer and use it in GitHub Desktop.
Save ataias/0a3239e5ac07ba1e0767 to your computer and use it in GitHub Desktop.
Scheduled NSTimer with a Swift closure
extension NSTimer {
/**
Creates and schedules a one-time `NSTimer` instance.
- Parameters:
- delay: The delay before execution.
- handler: A closure to execute after `delay`.
- Returns: The newly-created `NSTimer` instance.
*/
class func schedule(delay delay: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = delay + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, 0, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
/**
Creates and schedules a repeating `NSTimer` instance.
- Parameters:
- repeatInterval: The interval (in seconds) between each execution of
`handler`. Note that individual calls may be delayed; subsequent calls
to `handler` will be based on the time the timer was created.
- handler: A closure to execute at each `repeatInterval`.
- Returns: The newly-created `NSTimer` instance.
*/
class func schedule(repeatInterval interval: NSTimeInterval, handler: NSTimer! -> Void) -> NSTimer {
let fireDate = interval + CFAbsoluteTimeGetCurrent()
let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler)
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes)
return timer
}
}
// Usage:
var count = 0
NSTimer.schedule(repeatInterval: 1) { timer in
print(++count)
if count >= 10 {
timer.invalidate()
}
}
NSTimer.schedule(delay: 5) { timer in
print("5 seconds")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment