aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/cc/polyfrost/oneconfig/utils/TickDelay.java
blob: b7ee2c8e257dfb8538aea450b9a744decb10cfa0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package cc.polyfrost.oneconfig.utils;

import cc.polyfrost.oneconfig.events.EventManager;
import cc.polyfrost.oneconfig.events.event.Stage;
import cc.polyfrost.oneconfig.events.event.TickEvent;
import cc.polyfrost.oneconfig.libs.eventbus.Subscribe;

/**
 * Schedules a Runnable to be called after a certain amount of ticks.
 *
 * If the amount of ticks is below 1, the Runnable will be called immediately.
 */
public class TickDelay {
    private final Runnable function;
    private int delay;

    public TickDelay(Runnable functionName, int ticks) {
        if (ticks < 1) {
            functionName.run();
        } else {
            EventManager.INSTANCE.register(this);
            delay = ticks;
        }
        function = functionName;
    }

    @Subscribe
    protected void onTick(TickEvent event) {
        if (event.stage == Stage.START) {
            // Delay expired
            if (delay < 1) {
                function.run();
                EventManager.INSTANCE.unregister(this);
            }
            delay--;
        }
    }
}