Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2016-12-13

Implementing a delay in Swift

This is a simple post: we often need  delay in our software, so how to do that in Swift now dispatch_after has been changed beyond recognition?

There are multiple possibilities: use the "Thread.sleep" or use a timer instance are two of the often used. But both have drawbacks, the 'sleep' statement delays the actual thread that our code is running on, which degrades performance. And using (NS) Timer is too complex.

When I first looked at DispatchQueue.asyncAfter I hit a brick wall with doing arithmetic on DispatchTime or DispatchWallTime.

A second look at the Dispatch class showed the proper way to do this: simply add the delay not as a double but as a DispatchTimeInterval.

This code is so easy, it does not even need a wrapper:

        DispatchQueue.main.asyncAfter(
            deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(250),
            execute: {
                ...
            }

        )

Or even simpler:

        DispatchQueue.main.asyncAfter(
            deadline: .now() + .milliseconds(250),
            execute: {
                ...
            }
        )

Instead of milliseconds we can also choose from seconds, microseconds or even nanoseconds.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment