LoginSignup
4
3

More than 3 years have passed since last update.

Swift:Timer.scheduledTimerとDipatchQueue.main.asyncAfterの細かい違い

Posted at

n秒後に〇〇の処理を行うというようなプログラムを書く際,Timer.scheduledTimerDipatchQueue.main.asyncAfterを使うことになると思いますが,この2つには処理タイミングにズレがあるようです.

  • Timer.scheduledTimerはn秒後に(他の処理に割り込んででも)正確に処理が行われる
  • DipatchQueue.main.asyncAfterは最低n秒待ってから処理が行われる

つまり,Threadを指定して正確にn秒後にある処理をさせたい場合は,

Timer.scheduledTimer(withTimeInterval: 5.0, repeats: false) { (t) in
    DispatchQueue.main.async {
        // 処理
    }
}

という風にTimerの中でThreadを指定してやる必要がありそうです.

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3