简体   繁体   中英

How to put timeout to NSTimer in swift?

I have a NSTimer object as below :

 var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)

I want to put timeout to my timer. Maybe you know postdelayed method in android. I want to same thing's swift version. How can I do this ?

NSTimer is not suited for variable interval times. You set it up with one specified delay time and you can't change that. A more elegant solution than stopping and starting an NSTimer every time is to use dispatch_after .

Borrowing from Matt's answer :

// this makes a playground work with GCD
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

struct DispatchUtils {

    static func delay(delay:Double, closure:()->()) {
        dispatch_after(
            dispatch_time(
                DISPATCH_TIME_NOW,
                Int64(delay * Double(NSEC_PER_SEC))
            ),
            dispatch_get_main_queue(), closure)
    }
}


class Alpha {

    // some delay time
    var currentDelay : NSTimeInterval = 2

    // a delayed function
    func delayThis() {

        // use this instead of NSTimer
        DispatchUtils.delay(currentDelay) {
            print(NSDate())
            // do stuffs

            // change delay for the next pass
            self.currentDelay += 1

            // call function again
            self.delayThis()
        }
    }
}

let a = Alpha()

a.delayThis()

Try it in a playground. It will apply a different delay to each pass of the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM