Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Delay In A For Loop Without Blocking UI

In my UI, when a button is tapped, it calls a for loop that executes several tasks sequentially.

// For Loop
for (int i = 1; i <= 3; i++)
{
    // Perform Task[i]
}
// Results:
// Task 1
// Task 2
// Task 3

After each task, I would like add a user-defined delay. For example:

// For Loop
for (int i = 1; i <= 3; i++)
{
    // Perform Task[i]
    // Add Delay Here
}

// Results:
//
// Task 1
// Delay 2.5 seconds
//
// Task 2
// Delay 3 seconds
//
// Task 3
// Delay 2 seconds

In iOS, using Objective-C, is there a way to add such delays within a for loop, keeping in mind:

  1. The UI should remain responsive.
  2. The tasks must be performed in order, sequentially.

A code example within the context of a for loop would be most helpful. Thank you.

like image 414
Oak Avatar asked Feb 20 '26 18:02

Oak


2 Answers

Use GCD dispatch_after. You can search its usage on stackoverflow. Nice article is here

Brief example in Swift for 1.5 seconds delay:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 1.5)), dispatch_get_main_queue()) {
     // your code here after 1.5 delay - pay attention it will be executed on the main thread
}

and objective-c:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^ {
    // your code here after 1.5 delay - pay attention it will be executed on the main thread
});
like image 113
katleta3000 Avatar answered Feb 24 '26 17:02

katleta3000


This sounds like an ideal job for NSOperationQueue with the delay being implemented like this:

@interface DelayOperation : NSOperation
@property (NSTimeInterval) delay;
- (void)main
{
    [NSThread sleepForTimeInterval:delay];
}
@end
like image 36
l00phole Avatar answered Feb 24 '26 18:02

l00phole