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?
invalidate() is correct for stopping timer.
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()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With