Search code examples
iosnstimernstimeinterval

iOS: Get NSTimer to fire 5 seconds from now


THE SCENARIO I am working on an app that needs to fire off a method 5 seconds after a button is tapped.

THE CODE This is the code that is supposed to set off the controlTimerExpire method after 5 seconds

NSDate *fiveSecondsFromNow = [[NSDate date] dateByAddingTimeInterval:5.0f];
    NSTimeInterval timeInterval = [fiveSecondsFromNow timeIntervalSinceNow];

controlTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(controlTimerExpire) userInfo:nil repeats:NO];

// I ALSO TRIED THIS; HARDCODING IT LIKE BELOW

controlTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(controlTimerExpire) userInfo:nil repeats:NO];

THE ISSUE controlTimerExpire get fired immediately after the button is tapped. There needs to be 5 seconds in-between the button tap and the controlTimerExpire method firing.

THE QUESTION Why is this firing immediately and not firing 5 seconds from now?

LINKS What I have done above is exactly what these links below say to do, yet, it does not yield the same result as in the links. WHY?

Set an NSTimer to fire once in the future

How to call a method every x seconds in Objective-C using NSTimer?


Solution

  • The issue actually was further down in my code I was calling [controlTimer fire];. That was left over because I was trying to get it to work and I left that in there by mistake. Whoops, just wasted half an hour. So for you guys that may be having the same issue, all you need is to set the

    [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(controlTimerExpire) userInfo:nil repeats:NO];

    and you don't need to explicitly call fire because the scheduled part of the scheduledTimerWithTimeInterval will fire the selector for you based on the time interval you set.