in GCD, Programming

How to call a block after a delay

On iOS and on OS X you sometimes need the User Interface to update after a short delay. The old way of doing it was calling the performSelector:withObject:afterDelay: selector on any NSObject subclass but that requires defining a new method in your class and you can only pass one object as a parameter.

Instead, you can use dispatch_after from the Grand Central Dispatch APIs to execute code within a block after a certain time interval. Don’t be afraid, it might be low-level C but you can cut and paste and just put your code inside and it will retain the variable scope that blocks usually do!

double delayInSeconds = 0.5;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

  // Your code here

});

Write a Comment

Comment

  1. Here is how you can trigger a block after a delay in Swift:

    runThisAfterDelay(seconds: 2) { () -> () in
    print(“Prints this 2 seconds later in main queue”)
    }

    /// EZSwiftExtensions
    func runThisAfterDelay(seconds seconds: Double, after: () -> ()) {
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
    dispatch_after(time, dispatch_get_main_queue(), after)
    }

    Its included as a standard function in my repo:
    https://github.com/goktugyil/EZSwiftExtensions