Skip to content

Commit 6aa8729

Browse files
committed
Add start and stop instance methods to NSTimer
1 parent 552b420 commit 6aa8729

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

Src/SwiftyTimer.swift

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,17 +63,29 @@ extension NSTimer {
6363

6464
public class func after(interval: NSTimeInterval, _ block: () -> ()) -> NSTimer {
6565
let timer = NSTimer.new(after: interval, block)
66-
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
66+
timer.start()
6767
return timer
6868
}
6969

7070
/// Create and schedule a timer that will call `block` repeatedly in specified time intervals.
7171

7272
public class func every(interval: NSTimeInterval, _ block: () -> ()) -> NSTimer {
7373
let timer = NSTimer.new(every: interval, block)
74-
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
74+
timer.start()
7575
return timer
7676
}
77+
78+
/// Schedule this timer on the specified run loop (defaults to the current run loop)
79+
80+
public func start(onRunLoop runLoop: NSRunLoop = NSRunLoop.currentRunLoop(), forMode mode: String = NSDefaultRunLoopMode) {
81+
runLoop.addTimer(self, forMode: mode)
82+
}
83+
84+
/// Invalidate this timer (provided to match `start`)
85+
86+
public func stop() {
87+
self.invalidate()
88+
}
7789
}
7890

7991
extension Int {

Tests/SwiftyTimerTests/main.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,22 @@ class AppDelegate: NSObject, NSApplicationDelegate {
5050
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
5151
}
5252

53+
var timer4: NSTimer!
54+
5355
func test5() {
56+
var fired = false
57+
timer4 = NSTimer.new(every: 0.1.seconds) {
58+
if fired {
59+
self.timer4.stop()
60+
self.test6()
61+
} else {
62+
fired = true
63+
}
64+
}
65+
timer4.start()
66+
}
67+
68+
func test6() {
5469
NSTimer.after(0.1.seconds, done)
5570
}
5671

0 commit comments

Comments
 (0)