When it comes to handling an expensive computation within a function that is called frequently and needs to return quickly, my approach involves chaining promises together with this
. This method seems to be effective in ensuring that computations occur sequentially rather than rapidly.
let promiseChain = Promise.resolve();
function func() {
(async () => {
promiseChain = promiseChain.then(() => {
doComputation(); // does not provide a return value
});
})();
}
(Edit)
To elaborate further:
The actual implementation of the func
I am developing looks more like this:
function func() { // triggered whenever the DOM changes
const node = capture(document); // This essentially creates a clone of the DOM
(async () => {
promiseChain = promiseChain.then(() => {
doComputation(node); // does not provide a return value
});
})();
}
The reason for the necessity of quickly exiting from func
is due to rapid DOM changes, which need to be captured promptly. As a solution, running the content asynchronously within func
can aid in achieving this objective. While the computation itself may be synchronous and requires sequential execution, utilizing then
to chain them together serves this purpose effectively.