How to prevent ‘Stop running this script’ message in browsers

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, [])

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

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);

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).


Guido Tapia
Software Development Manager
PicNet Pty Ltd




About Guido Tapia

Over the last 2 years Guido has been involved in building 2 predictive analytics libraries for both the .Net platform and the Python language. These libraries and Guido's machine learning experience have placed PicNet at the forefront of predictive analytics services in Australia.

For the last 10 years Guido has been the Software and Data Manager at PicNet and in that time Guido has delivered hundreds of successful software and data projects. An experience architect and all round 'software guy' Guido has been responsible for giving PicNet its 'quality software provider' reputation.

Prior to PicNet, Guido was in the gaming space working on advanced graphics engines, sound (digital signal processing) engines, AI players and other great technologies.

Phone: +61 2 8437 7902

Interesting Links:
Kaggle Master Profile
Speaking Engagements and Conferences
PicNet Predictive Analytics Services