0

I like a timer to start when an object is created. (see code below in playground). My problem is the timer seem to never start.

How can I start a timer when a Object is created?

import Foundation

class Test {
    var counter = 60
    var timer = Timer()
    init() {
        timer = .scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
    }
    @objc func updateCounter() {
        // example functionality
        if counter > 0 {
            counter -= 1
            print(counter)
        } else {
            counter = 60
        }
    }
}

var newTest = Test()
0

1 Answer 1

2

What you need is to import PlaygroundSupport and set playground page needsIndefiniteExecution to true

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up to request clarification or add additional context in comments.

2 Comments

This is indeed the correct answer, (voted) but we should tell people why. Normally, playgrounds run top to bottom and then stop. Thus the timer is created but the playground code stops running before it can fire. By setting the playground page's needsIndefiniteExecution flag to true, the playground keeps running, and so does the users timer.
Thanks Duncan... I completely understand is now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.