|Written by Ian Elliot|
|Monday, 05 November 2018|
Page 1 of 3
Now Available as a Print Book:
You can buy it from: Amazon
To keep the UI responsive you have to let the UI thread do its job – which is to service the UI.
There are only two ways to do this:
In many ways using a separate thread is the best possible solution and it is the subject of the next chapter. However, using worker threads has its drawbacks. The biggest is that it isn't supported on all browsers and when it is some features vary. It can be difficult to write a multi-threaded program that works on all modern browsers.
There is also the problem of passing data between the threads and updating the UI in particular. For many simple cases managing the UI thread to do the work is an attractive option and it is certainly worth knowing what techniques are available to you to do so.
Custom Non-Blocking Functions
If you need a super efficient custom non-blocking function then you can use postMessage to add to the event queue without a minimum delay and this was also introduced in chapter Two.
But for simplicity let's start with setTimeout and return to postMessage later. We have already used them to implement true custom events, but their use in more general custom non-blocking functions is more important and worth going over again.
All you have to do is call setTimeout with a delay of zero:
This effectively puts the function on the event queue and then returns immediately. Of course, the function will not be processed by the event queue until the UI thread is released.
A simple example should make this clear:
You can see that the order of execution is not what you might expect, and this is typical asynchronous behavior. Notice also that the event queue is processed in whatever order the events occurred in, and if there is an event waiting to be processed it could be done before your custom function is called.
You can make use of this to break up a long running function so as to keep the UI responsive.
We have to arrange for the function to be "minimally" blocking by managing its use of the UI thread.
If you can't or don't want to use another thread then you have no choice but to divide up the calculation into small chunks. Each chunk should take a short enough time for the user not to notice that the UI isn't being serviced. The function has to restart after the break and it has to continue from where it left off. Notice that this introduces a new consideration into the mix and this is not just a matter of implementing a callback to use an existing non-blocking function, nor is it as simple as implementing a custom async event.
The general idea is very simple, but the details vary according to the algorithm.
|Last Updated ( Saturday, 10 November 2018 )|