SoFunction
Updated on 2025-04-03

Detailed explanation of how to implement millisecond countdown on iOS

Preface

Everyone should know that in app development, when displaying certain products with limited time offers, a countdown is often added to prompt users for the time remaining for the limited time offer of the product. For developers, what we need to implement is a countdown function. This countdown can be used in days, hours, minutes, seconds, and milliseconds according to specific needs.

Today, let’s talk about the millisecond timer. We know that the division between seconds and milliseconds is 1000, which means 1 second = 1000 milliseconds. When we do the millisecond countdown, we set a timer with a time interval of 1 millisecond to reduce the number of milliseconds one by one. But this is too time-consuming, so many millisecond timers have only numbers between 0 and 9, which means that the time interval of this millisecond timer is 100 milliseconds. This consumes much less than a timer with 1 millisecond interval, and it also achieves the effect of millisecond timing.

The idea for the entire millisecond countdown is to get the timestamp of a future date and the timestamp of the current date, calculate the time difference between the two, and then set a timer with a time interval of 100 milliseconds, and update the corresponding value on the countdown timer every 100 milliseconds.

Implementation method

Customize a UIview to encapsulate the countdown.

1. Add the two attributes of timestamp and timer

@interface MsecCountDownView : UIView

@property(nonatomic, assign)double timeInterval;//Time stamp of a future date@property(nonatomic, strong)NSTimer *timer ; //Timer
@end

2. Implementing related UI and countdown methods

@interface MsecCountDownView (){
UIView *countdownBackView;
CGFloat _passTime;
}
@property(nonatomic, strong)UILabel *tipLabel;
@property(nonatomic, strong)UILabel *hoursLabel;
@property(nonatomic, strong)UILabel *minutesLabel;
@property(nonatomic, strong)UILabel *secondsLabel;
@property(nonatomic, strong)UILabel *millionSecondsLabel;
@property(nonatomic, strong)UILabel *label1;
@property(nonatomic, strong)UILabel *label2;
@property(nonatomic, strong)UILabel *label3;
@property(nonatomic, strong)UILabel *label4;
@end

Create related UI

- (instancetype)initWithFrame:(CGRect)frame
{
 self = [super initWithFrame:frame];

 if (self) {

  countdownBackView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, , )];
  [self addSubview:countdownBackView];
  _tipLabel=[[UILabel alloc] init];
  _tipLabel.frame = CGRectMake(0, 0, 40, );
  [countdownBackView addSubview:_tipLabel];

  _tipLabel.font = [UIFont systemFontOfSize:12];


  //Hour  _hoursLabel=[[UILabel alloc] initWithFrame:CGRectMake(_tipLabel.+_tipLabel., 0, 35, )];
  [countdownBackView addSubview:_hoursLabel];
  _hoursLabel.font = [UIFont systemFontOfSize:11];

  _label1=[[UILabel alloc] initWithFrame:CGRectMake(_hoursLabel.+_hoursLabel., _hoursLabel., 8, )];
  [countdownBackView addSubview:_label1];

  //minute  _minutesLabel=[[UILabel alloc] initWithFrame:CGRectMake(_label1.+_label1., _hoursLabel., 20, )];
  [countdownBackView addSubview:_minutesLabel];
  _minutesLabel.font = [UIFont systemFontOfSize:11];

  _label2=[[UILabel alloc] initWithFrame:CGRectMake(_minutesLabel.+_minutesLabel., _hoursLabel., 8, )];
  [countdownBackView addSubview:_label2];

  //Second  _secondsLabel=[[UILabel alloc] initWithFrame:CGRectMake(_label2.+_label2., _hoursLabel., 20 , )];
  [countdownBackView addSubview:_secondsLabel];


  _secondsLabel.font = [UIFont systemFontOfSize:11];

  _label3=[[UILabel alloc] initWithFrame:CGRectMake(_secondsLabel.+_secondsLabel., _hoursLabel., 8 , )];
  [countdownBackView addSubview:_label3];


  _millionSecondsLabel=[[UILabel alloc] initWithFrame:CGRectMake(_label3.+_label3., _hoursLabel., 20, )];
  [countdownBackView addSubview:_millionSecondsLabel];


   //millisecond
  _millionSecondsLabel.font = [UIFont systemFontOfSize:11];

  _label1.textAlignment=1;
  _label2.textAlignment=1;
  _label3.textAlignment = 1;
  _hoursLabel.textAlignment=1;
  _minutesLabel.textAlignment=1;
  _secondsLabel.textAlignment=1;
  _millionSecondsLabel.textAlignment=1;


  _passTime=0.0;
 }


 return self;
}

Generate a timer

//Get the timestamp of a future date, and compared with the current timestamp, get the time difference between the two and generate a timer- (void)setTimeInterval:(double)timeInterval
{

 _timeInterval = timeInterval ;

 NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
  = @"MM/dd/yyyy HH:mm:";

 //Get the time of the current system and convert it in the corresponding format [dataFormatter stringFromDate:[NSDate date]];
 NSString *currentDayStr = [dataFormatter stringFromDate:[NSDate date]];
 NSDate *currentDate = [dataFormatter dateFromString:currentDayStr];

 //The time when the discount ends, it is also converted in the same format. NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval/1000.0];
 NSString *deadlineStr = [dataFormatter stringFromDate:date];
 NSDate *deadlineDate = [dataFormatter dateFromString:deadlineStr];

 _timeInterval=[deadlineDate timeIntervalSinceDate:currentDate]*1000;

 if (_timeInterval!=0)
 {

  //The time interval is 100 milliseconds, which is 0.1 second  _timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];

  [[NSRunLoop currentRunLoop] addTimer:_timer forMode:UITrackingRunLoopMode];
 }else{
  [countdownBackView removeFromSuperview];

 }

}

Implement the method of execution every 100 milliseconds and update the corresponding values ​​on the countdown timer

// The timer triggers execution of this method every 100 millisecond interval- (void)timerAction
{

 [self getTimeFromTimeInterval:_timeInterval] ;


 // Kill the timer when the time interval is 0 if (_timeInterval-_passTime == 0)
 {
  [_timer invalidate] ;
  _timer = nil ;
 }
}

// Calculate the specific time (hours, minutes, seconds, milliseconds)- (void)getTimeFromTimeInterval : (double)timeInterval
{

 //1s=1000ms _passTime += ;//The number of milliseconds is from 0-9, so each time 100 milliseconds pass _tipLabel.text=@"Left:";

 _label3.text=@".";
 _label2.text=@":";
 _label1.text=@":";

 //Hours NSString *hours = [NSString stringWithFormat:@"%ld", (NSInteger)((timeInterval-_passTime)/1000/60/60)];
 //Minutes NSString *minute = [NSString stringWithFormat:@"%ld", (NSInteger)((timeInterval-_passTime)/1000/60)%60];
 //Second NSString *second = [NSString stringWithFormat:@"%ld", ((NSInteger)(timeInterval-_passTime))/1000%60];
 //Milliseconds CGFloat sss = ((NSInteger)((timeInterval - _passTime)))%1000/100;


 NSString *ss = [NSString stringWithFormat:@"%.lf", sss];

 if ( < 10) {
  minute = [NSString stringWithFormat:@"0%@", minute];
 }


  = [NSString stringWithFormat:@"%@",hours];
  = [NSString stringWithFormat:@"%@",minute];
  = [NSString stringWithFormat:@"%@",second];
  = [NSString stringWithFormat:@"%@",ss];

 if (timeInterval - _passTime <= 0) {
  [countdownBackView removeFromSuperview];
  [self removeFromSuperview];
 }

}

3. Assign values ​​to the countdown to realize the countdown you want

- (void)viewDidLoad {
 [super viewDidLoad];

 msecView=[[MsecCountDownView alloc] initWithFrame:CGRectMake(50, 100, -100, 16)];
 [ addSubview:msecView];

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

 [formatter setDateStyle:NSDateFormatterMediumStyle];

 [formatter setTimeStyle:NSDateFormatterShortStyle];

 [formatter setDateFormat:@"yyyy-MM-dd HH:mm:"];


 NSDate* date = [formatter dateFromString:@"2017-04-11 15:10:00.000"];
 //Convert date to timestamp NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue]*1000;

 =timeSp;

}

This will realize the countdown function. However, you need to pay attention to using countdown. When leaving the page, remember to pause the timer and start the countdown when you return to the page.

This can be achieved through the following two methods.

-(void)viewWillAppear:(BOOL)animated{

// When the page appears, turn on the timer [ setFireDate:[NSDate distantPast]];

}
-(void)viewWillDisappear:(BOOL)animated{
// When the page disappears, pause the prompt [ setFireDate:[NSDate distantFuture]];
}

If necessary, you can download the demo through the following two methods

one:Download on GitHub

two:Local download

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.