Although not the original question by the OP, certain NSTimer related questions have been marked as duplicates of this question, so it is worth including an NSTimer answer here.
#NSTimer vs dispatch_after
NSTimeris more high level whiledispatch_afteris more low level.NSTimeris easier to cancel. Cancelingdispatch_afterrequires writing more codemore code.
#Delaying a task with NSTimer
Create an NSTimer instance.
var timer = NSTimer() Start the timer with the delay that you need.
// invalidate the timer if there is any chance that it could have been called before timer.invalidate() // delay of 2 seconds timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false) Add a function to be called after the delay (using whatever name you used for the selector parameter above).
func delayedAction() { print("Delayed action has now started." } #Notes
If you need to cancel the action before it happens, simply call
timer.invalidate().For a repeated action use
repeats: true.If you have a one time event with no need to cancel then there is no need to create the
timerinstance variable. The following will suffice:NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)