Kotlin Coroutines and Delay

By  on  

Whenever I suspect that there's a timing conflict causing a problem with rendering and directives, I usually opt for a JavaScript setTimeout with a delay. The setTimeout code never makes it to production, but it does help me to understand if my code is the problem or if there's a timing conflict.

In working with Kotlin on Android, I've needed to employ the same technique. Kotlin obviously doesn't have a setTimeout, but it does have coroutines to achieve approximately the same effect.

To run an async coroutine with delay, you can use the following Kotlin code:

// Create an async coroutine
GlobalScope.launch {
    delay(1000)
    
    // Execute code to test functionality
}

The coroutine becomes async and the delay can be whatever amount of milliseconds you'd like!

Recent Features

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

  • By
    JavaScript Promise API

    While synchronous code is easier to follow and debug, async is generally better for performance and flexibility. Why "hold up the show" when you can trigger numerous requests at once and then handle them when each is ready?  Promises are becoming a big part of the JavaScript world...

Incredible Demos

  • By
    Animated 3D Flipping Menu with CSS

    CSS animations aren't just for basic fades or sliding elements anymore -- CSS animations are capable of much more.  I've showed you how you can create an exploding logo (applied with JavaScript, but all animation is CSS), an animated Photo Stack, a sweet...

  • By
    Create Custom Events in MooTools 1.2

    Javascript has a number of native events like "mouseover," "mouseout", "click", and so on. What if you want to create your own events though? Creating events using MooTools is as easy as it gets. The MooTools JavaScript What's great about creating custom events in MooTools is...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!