import { world, system } from "@minecraft/server";

export function delay(ticks) {
    return new Promise(resolve => system.runTimeout(resolve, ticks));
}

export function delayCycle(ticks, cycle, limit=5) {
    if (++cycle < limit) {
        return cycle;
    } else {
        return new Promise(resolve => system.runTimeout(() => { resolve(0); }, ticks));
    }
}

export function intervalTimer(callbackFn, callbackArgs=[], interval=5, limit=10) {
    let cycle = 0;

    const runInterval = system.runInterval(() => {
        callbackFn(...callbackArgs);

        if (++cycle >= limit) {
            world.sendMessage(`Error: intervalTimer (${runInterval}) timed out.`)
            system.clearRun(runInterval);
        }

    }, interval);

    return runInterval;

}