From ffce12317f74d2414cd68c03d14f5f570b2d0bbd Mon Sep 17 00:00:00 2001 From: Aleksandr Guidrevitch Date: Sun, 18 Aug 2024 18:28:51 +0200 Subject: [PATCH] checkForQuiet bugfix to properly handle setTimeout() --- core/gather/driver/wait-for-condition.js | 48 +++++++++++++++--------- 1 file changed, 30 insertions(+), 18 deletions(-) diff --git a/core/gather/driver/wait-for-condition.js b/core/gather/driver/wait-for-condition.js index ac5b57f18b14..83b5bff22528 100644 --- a/core/gather/driver/wait-for-condition.js +++ b/core/gather/driver/wait-for-condition.js @@ -231,26 +231,37 @@ function waitForCPUIdle(session, waitForCPUQuiet) { /** * @param {ExecutionContext} executionContext - * @param {() => void} resolve * @return {Promise} */ - async function checkForQuiet(executionContext, resolve) { - if (canceled) return; - const timeSinceLongTask = - await executionContext.evaluate( - checkTimeSinceLastLongTaskInPage, {args: [], useIsolation: true}); - if (canceled) return; - - if (typeof timeSinceLongTask === 'number') { - if (timeSinceLongTask >= waitForCPUQuiet) { - log.verbose('waitFor', `CPU has been idle for ${timeSinceLongTask} ms`); - resolve(); - } else { - log.verbose('waitFor', `CPU has been idle for ${timeSinceLongTask} ms`); - const timeToWait = waitForCPUQuiet - timeSinceLongTask; - lastTimeout = setTimeout(() => checkForQuiet(executionContext, resolve), timeToWait); - } + function checkForQuiet(executionContext) { + if (canceled) { + return Promise.resolve(); } + + return executionContext.evaluate( + checkTimeSinceLastLongTaskInPage, {args: [], useIsolation: true}) + .then((timeSinceLongTask) => { + if (canceled) { + return; + } + + if (typeof timeSinceLongTask === 'number') { + if (timeSinceLongTask >= waitForCPUQuiet) { + log.verbose('waitFor', `CPU has been idle for ${timeSinceLongTask} ms`); + return; + } else { + log.verbose('waitFor', `CPU has been idle for ${timeSinceLongTask} ms`); + const timeToWait = waitForCPUQuiet - timeSinceLongTask; + return new Promise((resolve, reject) => { + lastTimeout = setTimeout(() => { + checkForQuiet(executionContext) + .then(resolve) + .catch(reject); + }, timeToWait); + }); + } + } + }); } /** @type {(() => void)} */ @@ -262,7 +273,8 @@ function waitForCPUIdle(session, waitForCPUQuiet) { /** @type {Promise} */ const promise = new Promise((resolve, reject) => { executionContext.evaluate(registerPerformanceObserverInPage, {args: [], useIsolation: true}) - .then(() => checkForQuiet(executionContext, resolve)) + .then(() => checkForQuiet(executionContext)) + .then(resolve) .catch(reject); cancel = () => { if (canceled) return;