Wednesday, July 25, 2007

Multithreading at JavaScript

Recently I've investigated how work multithreading at JavaScript and particulary IE. So, it is safe to say, there is no multithreading at JavaScript. All parts of script are running at the same thread.
Honestly, I expected that function setTimeout(func, timeInMillis) will run func at new htread. In effect this function just guaranties that func will be not runnig earlier than timeInMillis. Actually if you call it many times, all funcs will be added to the JavaScript engine queue. There is only one queue for all JavaScript at IE.

As for AJAX and particulary letter A, it is really asynchronous. When asynchronous request is posted it handling will run at other thread, but only before response receiving. If response received, callback function will be added to the JavaScript queue. So it will be asynchronous before response handling. Then it became full-synchronous.

Moreover all UI movements related to JavaScropt engine also run at the single thread. So if you have a long-running parts of script UI would be freeze. Thus for evading of UI freezing you need avoid a long-running parts of script. For example, this trick may be used for cycle evading:

iter = function() {
    if (i == 0) return;
    //peace of code
    setTimeout("writeLine();", 10);

setTimeout("iter(--i);", 0);

It is better to have many small parts than one big.

No comments: