Sleep, Pause or Block a Thread

If you ever need to briefly pause a thread of execution, there are two class methods in NSThread you can use. Although you have to use these methods judiciously, they can be handy in instances where you need to force a delay in order to achieve some desired effect.

For example, if you want to slowly fade-in (increase) the volume of the audio player over a few seconds, you could write a loop to bump the volume a small increment each time through the loop, and pause briefly before heading back to the top of the loop. If you didn’t include a short pause within the loop, the application may run the loop so quickly that you could not audibly detect the fade-in.

sleepForTimeInterval

One approach is to use the class method sleepForTimeInterval method:

+ (void)sleepForTimeInterval:(NSTimeInterval)ti

The variable NSTimeInterval is of type double and represents the number of seconds to sleep

// Block for .5 seconds
[NSThread sleepForTimeInterval:.5];
sleepUntilDate

Another approach is to use an NSDate object to specify a specific time in the future to resume the thread:

+ (void)sleepUntilDate:(NSDate *)aDate

With this method you pass in an NSDate object that specifies how long to block the thread.

// Block for 2.5 seconds from "now"
 NSThread sleepUntilDate: [NSDate dateWithTimeIntervalSinceNow:0.5]];
  1. What about using using performSelector:withObject:afterDelay: ? Wouldn’t that be simpler?

    • Hi Michelle,

      I think it depends on the context of what you need accomplish – for a simple loop like that shown below, using NSThread seems a reasonable approach:

      for (…)
      {
      player.volume += .1;
      [NSThread sleepForTimeInterval:.25];
      }

  2. Sure, that makes sense, so long as you don’t mind blocking the entire thread. BTW, do you generally use a separate thread for audio? I have a pending audio-based iPhone app and I’ve been planning a separate thread for each channel, but I’m not sure that’s the best architecture for the iPhone.

Comments are closed.