Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSTimer - how to delay in Swift

Tags:

ios

swift

nstimer

I have a problem with delaying computer's move in a game.

I've found some solutions but they don't work in my case, e.g.

var delay = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: nil, userInfo: nil, repeats: false) 

I tried to use this with function fire but also to no effects.

What other possibilities there are?

like image 666
Dandy Avatar asked Jan 16 '15 18:01

Dandy


People also ask

How do you make a delay in Swift?

Using asyncAfter block in Swift It is a built-in method of Grand central dispatch(GCD) API which helps us to add delay to our code execution in swift. The code that is to be delayed must be placed inside the asyncAfter() block. As a result, the code only executes after the specified time.

How do I set the timer on my swift5?

A perhaps more useful version of the block syntax: let timer = Timer. scheduledTimer(withTimeInterval: timeout, repeats: false) { _ in print("Done.") } You can't use 'let timer = Timer(timeInterval: 0.4, repeats: true) { _ in print("Done!") }' this will not start the timer and then you cannot get it to repeat.

How do I invalidate a timer in Swift?

invalidate() Stops the timer from ever firing again and requests its removal from its run loop.


1 Answers

Swift 3

With GCD:

let delayInSeconds = 4.0 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {      // here code perfomed with delay  } 

or with a timer:

func myPerformeCode() {     // here code to perform } let myTimer : Timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(self.myPerformeCode), userInfo: nil, repeats: false) 

Swift 2

With GCD:

let seconds = 4.0 let delay = seconds * Double(NSEC_PER_SEC)  // nanoseconds per seconds let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))  dispatch_after(dispatchTime, dispatch_get_main_queue(), {     // here code perfomed with delay  }) 

or with a timer:

func myPerformeCode(timer : NSTimer) {     // here code to perform } let myTimer : NSTimer = NSTimer.scheduledTimerWithTimeInterval(4, target: self, selector: Selector("myPerformeCode:"), userInfo: nil, repeats: false) 
like image 76
valfer Avatar answered Sep 19 '22 13:09

valfer