The unresponsive warning happens a couple of time a year but every time, it's frustrating. It prompts the message “A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete”.

I launched jskata not a long time ago and mostly talked about the undo feature. Now, I will talk about the jskata NoFreeze library to avoid freezing by splitting long processes into smaller ones.

You can look at the demo, the documentation or the source.

Old plain loop

This script loops the index variable from 0 to 1000000 and writes the current value in document.title. Unfortunately, it will freeze the page until the whole process is done.

var index = 0; // index
  for(index = 0; index <= 1000000; index++) {
      document.title = index;
  }

How to write a responsive for

I'm using jsKata.nofreeze library to avoid the freeze. This script will do the same as above. But, the page will remain responsive during the whole process.

var index = 0; // index
  jsKata.nofreeze.forloop(
      // the condition
      function() { return index <= 1000000;  }, 
      // the incrementor
      function() { index++; },
      // this is what will be executed
      function fct() {
          document.title = index;
      }
  );

It uses closures to keep a resemblance to a good ol' for loop.

Other loops : infinite and each

There are two other loops available. Infinite will loop indefinitely until you stop it. Each will loop through the properties of an object and loop in each one.

Take a look at the documentation to know more about them.

How to stop a process

As you see, every functions (forloop, infinite and each) return an object containing a stop function. So to stop a single process, just call it.

var loop = jsKata.nofreeze.infinite(function() {//do nothing});
  loop.stop();

If you want to stop all the processes of a page, make this call :

jsKata.nofreeze.stop();

More to come…

There's much more you can do with that library but I wanted to keep it simple for this post. Next, I'll talk about multi-process and other kinds of loop.