function waitForCPUIdle(session, waitForCPUQuiet) {
  if (!waitForCPUQuiet) {
    return {
      promise: Promise.resolve(),
      cancel: () => undefined,
    };
  }

  /** @type {NodeJS.Timeout|undefined} */
  let lastTimeout;
  let canceled = false;

  /**
   * @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);
      }
    }
  }

  /** @type {(() => void)} */
  let cancel = () => {
    throw new Error('waitForCPUIdle.cancel() called before it was defined');
  };

  const executionContext = new ExecutionContext(session);
  /** @type {Promise<void>} */
  const promise = new Promise((resolve, reject) => {
    executionContext.evaluate(registerPerformanceObserverInPage, {args: [], useIsolation: true})
      .then(() => checkForQuiet(executionContext, resolve))
      .catch(reject);
    cancel = () => {
      if (canceled) return;
      canceled = true;
      if (lastTimeout) clearTimeout(lastTimeout);
      reject(new Error('Wait for CPU idle canceled'));
    };
  });

  return {
    promise,
    cancel,
  };
}
Resolves when there have been no long tasks for at least waitForCPUQuiet ms.
@param {LH.Gatherer.ProtocolSession} session
@param {number} waitForCPUQuiet
@return {CancellableWait}