Cancel a timed event in Swift?

前端 未结 7 1868
说谎
说谎 2020-11-27 15:36

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

相关标签:
7条回答
  • 2020-11-27 16:24

    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()
    
    0 讨论(0)
提交回复
热议问题