Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel a timed event in Swift?

Tags:

events

swift

I want to run a block of code in 10 seconds from an event, but I want to be able to cancel it so that if something happens before those 10 seconds, the code won't run after 10 seconds have gone by.

I've been using this, but it's not cancellable:

static func delay(delay:Double, closure:()->()) {   dispatch_after(     dispatch_time(       DISPATCH_TIME_NOW,       Int64(delay * Double(NSEC_PER_SEC))     ),     dispatch_get_main_queue(), closure   ) } 

How can I accomplish this?

like image 573
Max Hudson Avatar asked Feb 06 '15 06:02

Max Hudson


People also ask

How do I stop a scheduled timer in Swift?

invalidate() is correct for stopping timer.


2 Answers

Swift 3 has DispatchWorkItem:

let task = DispatchWorkItem { print("do something") }  // execute task in 2 seconds DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2, execute: task)  // optional: cancel task task.cancel() 
like image 200
David Lawson Avatar answered Oct 04 '22 20:10

David Lawson


Update for Swift 3.0

Set Perform Selector

perform(#selector(foo), with: nil, afterDelay: 2) 

foo method will call after 2 seconds

 func foo()  {          //do something  } 

To cancel pending method call

 NSObject.cancelPreviousPerformRequests(withTarget: self) 
like image 34
Saumil Shah Avatar answered Oct 04 '22 20:10

Saumil Shah