Created
July 7, 2016 20:23
-
-
Save algal/31f2849119a303e4536a736ee3e07369 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// | |
// SettledownTimer.swift | |
// | |
// | |
// Created by Alexis Gallagher | |
// known-good: Swift 2.2, Xcode 7.3.1 | |
// | |
import Foundation | |
// not started : self.timer = nil | |
// running : self.timer != nil, isValid=true | |
// finished : self.timer != nil, isValid=false | |
/* | |
Use the SettleDownTimer in order to trigger FINAL_EVENT once only after | |
REPEATING_EVENT fails to happen within DURATION. | |
To use, configure the block to perform FINAL_EVENT. | |
Whenever REPEATING_EVENT happens, call restart(). The block will be called only once, after | |
`duration` from a call to `restart()`. | |
This can be used as a truly horrible hack to cause an event to happen only once | |
after layout completes. Not recommended! | |
*/ | |
class SettleDownTimer : NSObject { | |
private var timer:NSTimer? | |
let duration:NSTimeInterval | |
let block:()->() | |
init(duration:NSTimeInterval, block:() -> ()) { | |
self.duration = duration | |
self.block = block | |
super.init() | |
} | |
func restart() { | |
if let timer = self.timer { | |
// timer exists, so it is running or finished | |
if timer.valid { | |
// timer still running, so kill it and restart it | |
timer.invalidate() | |
self.timer = NSTimer.scheduledTimerWithTimeInterval(duration, target : self, selector : #selector(SettleDownTimer.doBlock), userInfo: nil, repeats : false) | |
} | |
else { | |
// timer finished, so do nothing | |
} | |
} | |
else { | |
// timer does not exist, so start it | |
self.timer = NSTimer.scheduledTimerWithTimeInterval(duration, target : self, selector : #selector(SettleDownTimer.doBlock), userInfo: nil, repeats : false) | |
} | |
} | |
func doBlock() { | |
self.block() | |
} | |
deinit { | |
if let timer = self.timer { | |
timer.invalidate() | |
} | |
self.timer = nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment