What is the Swift equivalent of "cleartimeout"?

I'm trying to set up a timeout on an input textbox that only implements the inner code a second after the user stops typing. So while the user was typing, I kept calling cleartimeout and rerunning setTimeout.

I originally looked at the performSelector function in Objective C, but it looks like there is no Swift equivalent for this.

Then I moved on to the GCD features in Swift looking for a way to accomplish this.

This is what I came up with:

var delta: Int64 = 1 * Int64(NSEC_PER_SEC)
var time = dispatch_time(DISPATCH_TIME_NOW, delta)
dispatch_suspend(dispatch_get_main_queue())
dispatch_after(time, dispatch_get_main_queue(), {
    println("timeout")
});

      

The dispatch_suspend function does not work as I hoped.

Perhaps the submit functions are not appropriate here?

+3


source to share


1 answer


dispatch_after

is a great alternative performSelect:afterDelay:

But I don't think any of them are what you want (because once you have them configured, there is no way to stop them).

If you only want to call a block of code after it has been idle for one second, I think you want to use a timer ( NSTimer

ok, for example , or you can use a dispatch timer). On the bottom line, every time you get keyboard interaction, see if there is a pending timer, and if so, invalid, then assign a new one.

So, I might be tempted to do something like Swift 3. For example, in iOS 10 and later, you can use block execution:

weak var timer: Timer?

func resetTimer() {
    timer?.invalidate()
    timer = .scheduledTimer(withTimeInterval: 1.0, repeats: false) { [weak self] timer in
        // do whatever you want when idle after certain period of time
    }
}

      

Or, if you need to support earlier versions of iOS that don't have block timers:



weak var timer: Timer?

func resetTimer() {
    timer?.invalidate()
    timer = .scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(handleIdleEvent(_:)), userInfo: nil, repeats: false)
}

func handleIdleEvent(_ timer: Timer) {
    // do whatever you want when idle after certain period of time
}

      

Or, in Swift 2:

weak var timer: NSTimer?

func resetTimer() {
    timer?.invalidate()
    let nextTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "handleIdleEvent:", userInfo: nil, repeats: false)
    timer = nextTimer
}

func handleIdleEvent(timer: NSTimer) {
    // do whatever you want when idle after certain period of time
}

      

By the way, I'm not sure what your intentions were dispatch_suspend

, but don't suspend the main queue. You never want to do anything that could potentially interfere with the main queue from handling events in a timely manner (i.e., never block / suspend the main queue).

+6


source







All Articles