refactor(waitFor): use GetGameTimer to timeout callbacks

Corrected error message output to ms.
Resolves #518.
This commit is contained in:
Linden
2024-03-18 18:48:57 +11:00
parent 591fb022f9
commit 2190cd32f4
2 changed files with 10 additions and 25 deletions

View File

@@ -10,31 +10,21 @@ function lib.waitFor(cb, errMessage, timeout)
if value ~= nil then return value end if value ~= nil then return value end
if timeout or timeout == nil then if timeout or timeout == nil then
if type(timeout) ~= 'number' then timeout = 1000 end if type(timeout) ~= 'number' then timeout = 1000 end
if IsDuplicityVersion() then
timeout /= 50;
else
timeout -= GetFrameTime() * 1000;
end
end end
local start = timeout and GetGameTimer()
local start = GetGameTimer()
local i = 0
while value == nil do while value == nil do
if timeout then Wait(0)
i += 1
if i > timeout then local elapsed = timeout and GetGameTimer() - start
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 end
Wait(0)
value = cb() value = cb()
end end

View File

@@ -93,7 +93,7 @@ export interface VehicleProperties {
modLightbar: number; modLightbar: number;
windows: number[]; windows: number[];
doors: number[]; doors: number[];
tyres: Record<number | string, 1 | 2> tyres: Record<number | string, 1 | 2>;
leftHeadlight: boolean; leftHeadlight: boolean;
rightHeadlight: boolean; rightHeadlight: boolean;
frontBumper: boolean; frontBumper: boolean;
@@ -113,22 +113,17 @@ export async function waitFor<T>(cb: () => T, errMessage?: string, timeout?: num
if (timeout || timeout == null) { if (timeout || timeout == null) {
if (typeof timeout !== 'number') timeout = 1000; if (typeof timeout !== 'number') timeout = 1000;
if (IsDuplicityVersion()) timeout /= 50;
else timeout -= GetFrameTime() * 1000;
} }
const start = GetGameTimer(); const start = GetGameTimer();
let id: number; let id: number;
let i = 0;
const p = new Promise<T>((resolve, reject) => { const p = new Promise<T>((resolve, reject) => {
id = setTick(async () => { id = setTick(async () => {
if (timeout) { const elapsed = timeout && GetGameTimer() - start;
i++;
if (i > timeout) if (elapsed && elapsed > (timeout as number)) {
return reject(`${errMessage || 'failed to resolve callback'} (waited ${(GetGameTimer() - start) / 1000}ms)`); return reject(`${errMessage || 'failed to resolve callback'} (waited ${elapsed}ms)`);
} }
value = await cb(); value = await cb();