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 The Author

Guido Tapia

Chief Technology Officer – Software Development. Guido has led the development of Enterprise Risk Management system Risk Shield and the award winning web application, Mouse Eye Tracking - a usability tool that reveals website visitor activity. In addition has led numerous software projects for blue chip Australian organisations and specialises in Java, .Net and Javascript development.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>