Skip to content

Commit

Permalink
checkForQuiet bugfix to properly handle setTimeout()
Browse files Browse the repository at this point in the history
  • Loading branch information
aguidrevitch committed Aug 18, 2024
1 parent c79628a commit ffce123
Showing 1 changed file with 30 additions and 18 deletions.
48 changes: 30 additions & 18 deletions core/gather/driver/wait-for-condition.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,26 +231,37 @@ function waitForCPUIdle(session, waitForCPUQuiet) {

/**
* @param {ExecutionContext} executionContext
* @param {() => void} resolve
* @return {Promise<void>}
*/
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)} */
Expand All @@ -262,7 +273,8 @@ function waitForCPUIdle(session, waitForCPUQuiet) {
/** @type {Promise<void>} */
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;
Expand Down

0 comments on commit ffce123

Please sign in to comment.