Montag, Mai 30, 2005

Why asynchronous programming (2)?

How asynchronous programming is done in the browser and why it doesn’t work always.

Here, the sample from the preceding posting is continued.

Complicated and long running functions have the unpleasant characteristic, that during their execution all the other activities are standing still. In particular really long running functions represent a genuine problem and therefore both browsers the Microsoft Internet Explorer and Firefox are offering the possibility of a brutal termination of execution.

[A script on this page may be busy, or it may have stopped responding. ...]

The way out of this dilemma is possible when using a parallel execution of the calculation of the factors and the handling of all user interface events like keystrokes.In the Browser and with the assistance of Javascript there is only a very much limited way of parallel execution with the assistance of a timer and events possible. However the problems and the realizations of such parallel algorithms must be suitable for this. When a Javascript function runs then the Events from the user inputs are no longer directly processed and the application appears blocked again.

Implementing this can be done in the following way: With every keystroke a timeout (_timer) is registered to trigger the calculation of the factors. The chosen timeout is just a little bit longer than the time a normal user needs in-between typing the characters. If a new character is typed in, the running timeout is canceled and a new timeout is registered. The calculation of the factors remains identical.


For guaranteed short running functions this kind of the implementation is very helpful for the user. The delay in the case, that the calculation is executed is hardly noticed and an input of a further character or a click with the mouse is executed only some milliseconds later.But with long running functions, like with large numbers a problem will arise.

I know 2 Methods of solving this: 1. Divide the long running function into several smaller functions 2. Real parallel execution with the assistance of a server (let's AJAX)

For sure it is possible to changed many algorithms in such a way so that instead of a long running method several shorter steps are lined up. With the sample of the computation of the prime factors this is also possible. The timer is used in very short timeout intervals to check a new prime number candidate.


However, the result is very discouraging, because the running time of a complete computation rises up with an intolerable factor so far, that the practice fitness is no longer given.Beside the problem, that everything runs more slowly exists also the problem that local variables cannot be used any more. All information about the current state must be stored in global variables to be available for the next step. That is not very useful kind of programming and again reminds me of the "good old times" of the 80's.