Skip to content

Instantly share code, notes, and snippets.

@ispiropoulos
Created December 14, 2016 10:07
Show Gist options
  • Save ispiropoulos/3dcac4ff08cb499821bd91b0cb66d7c9 to your computer and use it in GitHub Desktop.
Save ispiropoulos/3dcac4ff08cb499821bd91b0cb66d7c9 to your computer and use it in GitHub Desktop.
Swift Timer with Block
//
// 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