import { setTimeout as setTimeoutInternal } from "./timer";
function setTimeout(fn: () => void, delay: i32): i32 {
const wrapper = (userData: i32): void => {
ffi.set_ffi_closure_env(userData);
fn();
};
return setTimeoutInternal(wrapper.index, delay, wrapper.env);
}
function sleep(delay: i32): Promise<void> {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, delay);
});
}
export function _start(): void {
trace(`_start`);
let a = 10;
sleep(1000).then(() => {
trace(`sleep done`);
a += 20;
trace(`a: ${a}`);
});
}
class Promise<T> {
result: T | null = null;
thenCallbacks: ((value: T) => void) | null = null;
constructor(cb: (resolve: (value: T) => void) => void) {
cb((value: T) => {
this.result = value;
if (this.thenCallbacks) {
this.thenCallbacks(value);
}
});
}
then(cb: (value: T) => void): void {
if (this.result !== null) {
cb(this.result);
} else {
this.thenCallbacks = cb;
}
}
}