diff --git a/core/gather/driver/wait-for-condition.js b/core/gather/driver/wait-for-condition.js index ac5b57f18b14..55207ee63d08 100644 --- a/core/gather/driver/wait-for-condition.js +++ b/core/gather/driver/wait-for-condition.js @@ -225,32 +225,41 @@ function waitForCPUIdle(session, waitForCPUQuiet) { }; } - /** @type {NodeJS.Timeout|undefined} */ - let lastTimeout; let canceled = false; /** * @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) => { + setTimeout(() => { + checkForQuiet(executionContext) + .then(resolve) + .catch(reject); + }, timeToWait); + }); + } + } + }); } /** @type {(() => void)} */ @@ -262,12 +271,12 @@ 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; canceled = true; - if (lastTimeout) clearTimeout(lastTimeout); reject(new Error('Wait for CPU idle canceled')); }; });