In Search For a Solution
In order to see what could solve this issue, we must realize where the problem exists. In a simple while loop, the engine evaluates a condition, and if true executes a block of code, then does this process until the condition evaluates to false.
The problem with doing this is also the inherit benefit — and likely the reason that you, the developer, chose to use a while loop in this function: a while loop runs for a non-fixed amount of time. An amount of time that is entirely dependent on the values associated with the condition and the block of code in the loop. This causes all of the queued up events (requests, button presses, etc.) to have to wait, making the user think your web app is slow and crappy.
The Solution To This
In order to stick with the original design strategy of our function, we’re going to have to change the way we write our code; we’re going to have to play with the JS Engine, as opposed to fighting with it. Let’s make a checklist of what we want:
- We need to check a condition.
- If that condition is true, we should run the specified block of code.
- Repeat the cycle, until the condition is not true, then continue with the rest of the function.
What Our Code Currently Looks Like
Where To Go From Here
Now To Make The While Loop Non-Blocking
This is probably the most interesting part of this process: we are going to take a block of code that could potentially block up the whole system, and make it play fairly with the rest of the executing code (by not hogging up the single thread).
This allows the user to have a great, speedy UI. And for NodeJS server requests to respond to other requests quicker. And once the condition fails, in the else section we call the afterWhileLoop callback.
Hopefully, this generalized tutorial has helped you break down exactly how to make blocking actions non-blocking. There are cleaner ways to write it, especially using Immediately Invoking Functions (see below), but I want it to be very clear to help make it easy to understand.
As we can see, it’s an increase from about 10 lines originally, to now 20 lines, but your users and clients will love you for it!
Thanks for reading my post,
-Max Dignan — https://twitter.com/maxdignan