Interleaving with the setImmediate Function

Learn how to use the interleaving with the setImmediate method to manage concurrent requests in Node.js applications.

Usually, a CPU-bound algorithm is built upon a set of steps. This can be a set of recursive invocations, a loop, or any variation/combination of these. So, a simple solution to our problem would be to give the control back to the event loop after each step completes (or after a certain number of them). This way, any pending I/O requests can still be processed by the event loop in those intervals in which the long-running algorithm yields the CPU. A simple way to achieve this is to schedule the next step of the algorithm to run after any pending I/O requests. This sounds like the perfect use case for the setImmediate() function.

Interleaving the steps of the subset sum algorithm

Let’s now see how this technique applies to our subset sum algorithm. All we have to do is slightly modify the subsetSum.js module. For convenience, we’re going to create a new subsetSumDefer.js named module, taking the code of the original subsetSum class as a starting point.

The first change we’re going to make is to add a new  _combineInterleaved() named method, which is the core of the technique we’re implementing.

Get hands-on with 1200+ tech skills courses.