diff --git a/src/kernel/EndOfLoop.hx b/src/kernel/EndOfLoop.hx new file mode 100644 index 0000000..1da504f --- /dev/null +++ b/src/kernel/EndOfLoop.hx @@ -0,0 +1,24 @@ +package kernel; + +import cc.OS; + +/** + Make sure that a function is called at the end of the current event loop. + Like setTimeout(func, 0) in JavaScript. +**/ +class EndOfLoop { + private static var backlog:Array Void> = []; + private static var isQueued = false; + + public static function endOfLoop(func: Void -> Void) { + backlog.push(func); + if (!isQueued) { OS.queueEvent("endofloop", null); } + } + + @:allow(kernel.KernelEvents) + private static function run() { + for (func in backlog) { func(); } + backlog = []; + isQueued = false; + } +} diff --git a/src/kernel/KernelEvents.hx b/src/kernel/KernelEvents.hx index 7486941..b8dd6bf 100644 --- a/src/kernel/KernelEvents.hx +++ b/src/kernel/KernelEvents.hx @@ -228,6 +228,8 @@ class KernelEvents { this.onWebsocketMessageTrigger.trigger({url: event[2], message: event[3], isBinary: event[4]}); case "websocket_success": this.onWebsocketSuccessTrigger.trigger({url: event[2], handle: event[3]}); + case "endofloop": + EndOfLoop.run(); default: Log.error('Unknown event: $eventName'); }