BadmintonCat
BadmintonCat

Reputation: 9586

Timer Interval not firing

Consider this code:

import Foundation
import PlaygroundSupport

class Test
{
    var interval:Timer?
    var counter = 0

    func start()
    {
        print("Starting ...")
        interval = Timer.scheduledTimer(withTimeInterval: 1, repeats: true)
        {
            timer in
            self.counter += 1
            print(self.counter)
            if (self.counter < 10) { return }

            self.interval?.invalidate()
            self.interval = nil
            print("Done!")
            PlaygroundPage.current.finishExecution()
        }
        interval?.fire()
    }
}


PlaygroundPage.current.needsIndefiniteExecution = true
var test = Test()
test.start()

Running this in Xcode 8.3.3 Playground but the interval never starts. What am I'm missing?

Upvotes: 0

Views: 188

Answers (1)

Kevin
Kevin

Reputation: 56129

The simple answer is to add this to your playground:

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

When using a playground, by default the playground runs all the code and then stops, it doesn't know to wait for the timer. This code just tells the playground to keep waiting for something to happen.

Upvotes: 1

Related Questions