Jake Silverman Jake Silverman - 2 years ago 107
Swift Question

How can I make an NSTimer that repeats a specific number of times?

I want to call a function 50 times every .5 seconds using an NSTimer, but my only options are to have the timer run indefinitely or to create timers that are not repeating. Can I get away with using timers to do what I want, or should I try using something else?

Answer Source

You just need to keep track of the number of function call using a class variable.

Once the max number of function call is met, you stop setting the next timer.

Using an iOS UIViewController class as an example:

class ViewController: UIViewController {

    var timer:NSTimer? = nil;
    var times:Int = 0;

    override func viewDidLoad() {

    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

    func startTimer() {

        timer = NSTimer.scheduledTimerWithTimeInterval(0.5, 
                                                 target: self, 
                                                 selector: "onTick:", 
                                                 userInfo: nil,
                                                 repeats: false)


    func onTick(timer:NSTimer){
        println("Fired \(self.times)")
        times += 1
        // call your function
        if times < 50 {  // set the next timer 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download