From 2190cd32f40ecbc4dddd6f5c2be4bd557a195084 Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Mon, 18 Mar 2024 18:48:57 +1100 Subject: [PATCH] refactor(waitFor): use GetGameTimer to timeout callbacks Corrected error message output to ms. Resolves #518. --- imports/waitFor/shared.lua | 22 ++++++---------------- package/shared/index.ts | 13 ++++--------- 2 files changed, 10 insertions(+), 25 deletions(-) diff --git a/imports/waitFor/shared.lua b/imports/waitFor/shared.lua index 0da28960..2492adcb 100644 --- a/imports/waitFor/shared.lua +++ b/imports/waitFor/shared.lua @@ -10,31 +10,21 @@ function lib.waitFor(cb, errMessage, timeout) if value ~= nil then return value end - if timeout or timeout == nil then if type(timeout) ~= 'number' then timeout = 1000 end - - if IsDuplicityVersion() then - timeout /= 50; - else - timeout -= GetFrameTime() * 1000; - end end - - local start = GetGameTimer() - local i = 0 + local start = timeout and GetGameTimer() while value == nil do - if timeout then - i += 1 + Wait(0) + + local elapsed = timeout and GetGameTimer() - start - if i > timeout then - return error(('%s (waited %.1fms)'):format(errMessage or 'failed to resolve callback', (GetGameTimer() - start) / 1000), 2) - end + if elapsed and elapsed > timeout then + return error(('%s (waited %.1fms)'):format(errMessage or 'failed to resolve callback', elapsed), 2) end - Wait(0) value = cb() end diff --git a/package/shared/index.ts b/package/shared/index.ts index a9e319dd..92597cb8 100644 --- a/package/shared/index.ts +++ b/package/shared/index.ts @@ -93,7 +93,7 @@ export interface VehicleProperties { modLightbar: number; windows: number[]; doors: number[]; - tyres: Record + tyres: Record; leftHeadlight: boolean; rightHeadlight: boolean; frontBumper: boolean; @@ -113,22 +113,17 @@ export async function waitFor(cb: () => T, errMessage?: string, timeout?: num if (timeout || timeout == null) { if (typeof timeout !== 'number') timeout = 1000; - - if (IsDuplicityVersion()) timeout /= 50; - else timeout -= GetFrameTime() * 1000; } const start = GetGameTimer(); let id: number; - let i = 0; const p = new Promise((resolve, reject) => { id = setTick(async () => { - if (timeout) { - i++; + const elapsed = timeout && GetGameTimer() - start; - if (i > timeout) - return reject(`${errMessage || 'failed to resolve callback'} (waited ${(GetGameTimer() - start) / 1000}ms)`); + if (elapsed && elapsed > (timeout as number)) { + return reject(`${errMessage || 'failed to resolve callback'} (waited ${elapsed}ms)`); } value = await cb();