Monday, July 23, 2007

Avoiding 'Slow Script' Errors

So, you need to render 2,968 widgets to the DOM? Or, you really, really rather compute your data on the client, because the architectural geniuses you work with never thought you would want to cross-relate these two data sets, and it will be a load of work to re-architecture the back-end to handle this task? Well generally, my advice would be to avoid doing such tasks on the client, but that is not because it is not possible.

Sometimes when prototyping algorithms or cross-linked data presentations, I find myself pushing the computational barrier of JavaScript. Anyone who has done this, has managed to repeatedly trigger the 'Slow Script' warning asking the user to either stop or continue. These messages are easy to avoid with a little code modification.


function RenderDataSet(start) {
var SEGMENT_SIZE = 100;
var index = 0 + start;
do {
RenderData(index);
index++;
}
while (index < dataset.length
&& index < start+SEGMENT_SIZE);

if (index<DataSet.length)
setTimeout("RenderDataSet("+index+");",1);
}

Since you are only allowed a few seconds of the thread's time to carry out your task, and there is no forking or spawning available for you to make new threads, you simply have to rely on setTimeout(expr,time). This releases the thread for a very small fraction of a second to allow other browser actions to occur. This is also a good practice to get into for real-time applications as well, since expensive tasks can slow down other features of your web application.