Created
December 14, 2016 10:07
-
-
Save ispiropoulos/3dcac4ff08cb499821bd91b0cb66d7c9 to your computer and use it in GitHub Desktop.
Swift Timer with Block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// JSBlockTimer.swift | |
// | |
// | |
// Created by John Spiropoulos on 14/12/2016. | |
// Copyright © 2016 John Spiropoulos. All rights reserved. | |
// | |
/* | |
Usage: | |
duration: How long do you want the timer to be active? (in seconds) | |
interval: The repetition interval of the timer (in seconds) | |
_ = JSBlockTimer(duration: 2, interval: 2, block: { (elapsedSecs) in | |
UIView.animate(withDuration: 0.3, animations: { | |
self.splitPopUpImage.alpha = 0 | |
}) | |
}).start() | |
*/ | |
class JSBlockTimer { | |
var timer = Timer() | |
var block: (Int) -> () | |
let duration: Int | |
let interval: TimeInterval | |
var elapsedTime: Int = 0 | |
init(duration: Int, interval: TimeInterval, block: @escaping (Int) -> ()) { | |
self.duration = duration | |
self.interval = interval | |
self.block = block | |
} | |
func start() { | |
self.timer = Timer.scheduledTimer(timeInterval: interval, | |
target: self, | |
selector:#selector(eachSecond), | |
userInfo: nil, | |
repeats: true) | |
} | |
func stop() { | |
timer.invalidate() | |
} | |
@objc func eachSecond() { | |
self.elapsedTime+=1 | |
self.block(elapsedTime) | |
if self.elapsedTime == self.duration { | |
self.stop() | |
} | |
} | |
deinit { | |
self.timer.invalidate() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment