How do I use delay instead of Thread.sleep in Kotlin coroutines?

Use kotlinx.coroutines.delay(...) inside a coroutine instead of Thread.sleep(...).

Thread.sleep blocks the current thread. delay suspends the coroutine without blocking the thread, so other coroutines can keep running.

import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    println("Before delay")

    delay(1_000) // suspends for 1 second, does not block the thread

    println("After delay")
}

If you currently have:

Thread.sleep(1000)

replace it with:

delay(1000)

But note: delay is a suspend function, so it can only be called from another suspend function or from inside a coroutine builder such as launch, async, or runBlocking.

Example with launch:

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    launch {
        delay(1000)
        println("Coroutine finished after 1 second")
    }

    println("This prints immediately")
}

Example in a suspend function:

import kotlinx.coroutines.delay

suspend fun doWork() {
    delay(500)
    println("Work done")
}

Avoid doing this in coroutines:

Thread.sleep(1000) // blocks the underlying thread

Prefer:

delay(1000) // suspends only the coroutine

How do I set Swing Timer initial delay?

The Swing javax.swing.Timer object fires the action event after the delay time specified in the constructor passed. For some reasons you might want the Timer class fires immediately after it was started.

To achieve this you can set the timer initial delay by calling the setInitialDelay(int initialDelay) method. The example below give you an example how to do it.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TimerInitialDelayDemo extends JFrame {
    private final JLabel counterLabel = new JLabel();

    private Timer timer = null;

    public TimerInitialDelayDemo() throws HeadlessException {
        initUI();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new TimerInitialDelayDemo().setVisible(true));
    }

    private void initUI() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 500);

        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.CENTER));
        container.add(counterLabel);

        timer = new Timer(1000, new MyActionListener());

        // Set initial delay of the Timer object. Setting initial delay
        // to zero causes the timer fires the event immediately after
        // it is started.
        timer.setInitialDelay(0);
        timer.start();
    }

    class MyActionListener implements ActionListener {
        private int counter = 10;

        public void actionPerformed(ActionEvent e) {
            counter = counter - 1;
            String text = "<html><font size='14'>" +
                    counter +
                    "</font></head>";
            counterLabel.setText(text);
            if (counter == 0) {
                timer.stop();
            }
        }
    }
}

How do I add a delay in my program?

You have a problem that you want to add a delay for a couple of seconds in your program. Using Thread.sleep() method we can add delay in our application in a millisecond time. The Thread.sleep() need to be executed inside a try-catch block, and we need to catch the InterruptedException. Let’s see the code snippet below.

package org.kodejava.lang;

public class DelayExample {
    public static void main(String[] args) {
        // This program demonstrate how to add a delay in our 
        // application.
        for (int i = 0; i < 10; i++) {
            // Print the value of i
            System.out.println("i = " + i);

            try {
                // Using Thread.sleep() we can add delay in our 
                // application in a millisecond time. For the example 
                // below the program will take a deep breath for one 
                // second before continue to print the next value of 
                // the loop.
                Thread.sleep(1000);

                // The Thread.sleep() need to be executed inside a 
                // try-catch block and we need to catch the 
                // InterruptedException.
            } catch (InterruptedException ie) {
                ie.printStackTrace();
            }
        }
    }
}