How to prevent 'Stop running this script' message in browsers

by Guido Tapia

in software-engineering,

March 4, 2010

Avoiding the ‘Script taking too long’ (all browsers have some form or another of this) message in browsers is relatively simple. You just have to make sure the browser knows you have not created an endless loop or recursion. And the easiest way to do is is to just give the browser a breather in between long running tasks.

So how would we go about this. Well the simplest solution is to just break up your task into mutliple smaller tasks with a setTimeout in between these tasks. The utility class below does just this:

Utility Class

RepeatingOperation = function(op, yieldEveryIteration) {
  var count = 0;
  var instance = this;
  this.step = function(args) {
    if (++count >= yieldEveryIteration) {
      count = 0;
      setTimeout(function() { op(args); }, 1, [])
      return;
      }
    op(args);
  };
};

So how do we use this class, lets say we have the following code which is giving us a jerky browser and occasionally displaying those horrible ‘Stop running this script’ message:

// initdata is just an array of numbers (a very very large array)
var test1 = new Array(initdata.length);
for (var i = 0; i < initdata.length; i++) { test1[i]  = initdata[i] * 2; } // Double each item in the initdata array
continueOperations();

To use the utility class above we would change the code to this:

var test2 = new Array(initdata.length);
var i = 0;
var ro = new RepeatingOperation(function() {
  test2[i] = initdata[i] * 2;
  if (++i < initdata.length) { ro.step(); }
  else { continueOperations(); }
  }, 100);
ro.step();

That’s it, a little bit more code, an extra closure, so not pretty but I think a relativelly stylish solution to a nasty problem. Note: Remember this will also give you a much more responsive browser during execution of this expensive code also.

Note: This solution is used in the Mouse Eye Tracking system. So it is production ready (at your own risk tho).

Thanks

Guido Tapia Software Development Manager PicNet Pty Ltd