简体   繁体   English

如何快速暂停NSTimer?

[英]How to put timeout to NSTimer in swift?

I have a NSTimer object as below : 我有一个NSTimer对象,如下所示:

 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. 也许您知道android中的postdelayed方法。 I want to same thing's swift version. 我想要同一件事的快速版本。 How can I do this ? 我怎样才能做到这一点 ?

NSTimer is not suited for variable interval times. NSTimer不适合可变间隔时间。 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 . 与每次停止和启动NSTimer相比,更优雅的解决方案是使用dispatch_after

Borrowing from Matt's answer : 借用Matt的答案

// 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. 它将对函数的每次通过施加不同的延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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