@itwin/core-bentley
Version:
Bentley JavaScript core components
44 lines • 2.03 kB
JavaScript
;
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module Utils
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.YieldManager = void 0;
const defaultYieldManagerOptions = {
iterationsBeforeYield: 1000,
};
/** Provides a mechanism by which a loop can be made to periodically yield control back to the browser/node environment.
* This can alleviate [performance and memory consumption issues](https://github.com/nodejs/node-addon-api/issues/1140).
* It maintains a count of the number of iterations that have occurred since the last yield.
* The constructor specifies how many iterations of the loop are permitted before yielding.
* The loop should `await` [[allowYield]] on each iteration.
* [[allowYield]] will yield (and reset the iteration counter) if the counter exceeds the specified maximum.
* @public
*/
class YieldManager {
/** Options controlling the yield behavior. */
options;
_counter = 0;
/** Constructor.
* @param options Options customizing the yield behavior. Omitted properties are assigned their default values.
*/
constructor(options = {}) {
this.options = { ...defaultYieldManagerOptions, ...options };
}
/** Increment the iteration counter, yielding control and resetting the counter if [[options.iterationsBeforeYield]] is exceeded. */
async allowYield() {
this._counter = (this._counter + 1) % this.options.iterationsBeforeYield;
if (this._counter === 0) {
await this.actualYield();
}
}
async actualYield() {
await new Promise((r) => setTimeout(r, 0));
}
}
exports.YieldManager = YieldManager;
//# sourceMappingURL=YieldManager.js.map