From eab47c66b6e0c8c9a6d2667cd5fbc17190f24485 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Mon, 28 Nov 2022 23:17:15 +0100 Subject: [PATCH] Ensure busy wait does not end before promise fullfiling MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- busy-wait.js | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/busy-wait.js b/busy-wait.js index 9d0d31b..66d5896 100644 --- a/busy-wait.js +++ b/busy-wait.js @@ -15,11 +15,12 @@ function dummyTimeoutBusyWait (timeoutMs) { /** * @param timeoutMs + * @param intervalMs */ -async function sleepTimeoutBusyWait (timeoutMs) { +async function sleepTimeoutBusyWait (timeoutMs, intervalMs = interval) { const timeoutTimestampMs = Date.now() + timeoutMs do { - await sleep(interval) + await sleep(intervalMs) } while (Date.now() < timeoutTimestampMs) } @@ -43,13 +44,14 @@ async function divideAndConquerTimeoutBusyWait ( * @param timeoutMs * @param intervalMs */ -function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) { +async function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) { const tries = Math.round(timeoutMs / intervalMs) let count = 0 const triesSetInterval = setInterval(() => { count++ if (count === tries) { clearInterval(triesSetInterval) + return Promise.resolve() } }, intervalMs) } @@ -65,8 +67,8 @@ Benchmark.suite( Benchmark.add('divideAndConquerTimeoutBusyWait', async () => { await divideAndConquerTimeoutBusyWait(timeout) }), - Benchmark.add('setIntervalTimeoutBusyWait', () => { - setIntervalTimeoutBusyWait(timeout) + Benchmark.add('setIntervalTimeoutBusyWait', async () => { + await setIntervalTimeoutBusyWait(timeout) }), Benchmark.cycle(), Benchmark.complete(), -- 2.34.1