I noticed a question on here the other day ( Reducing Javascript CPU Usage ) and I was intrigued.

Essentially the guy wanted to encrypt some files character by character. Obviously doing all this in one go is going to lock up the browser.

His first idea was to do it in chunks roughly 1kb's worth of string at a time, then pause for X ms so it would allow the user to keep interacting with the page between processing. He also considered using webWorkers ( the best idea ), but it obviously isn't cross browser.

Now I don't really want to go into why this probably isn't a good idea in javascript. But I wanted to see if I could come up with a solution.

I remembered watching a video by Douglas Crockford at js conf. The video was related to node.js and the event loop. But I remembered him talking about breaking long running functions down into individual chunks, so the newly called function goes to the end of the event loop. Instead of clogging the event loop up with a long running task, preventing anything else from happening.

I knew this was a solution worthy of my investigation. As a front-end Developer I have never really experienced extremely long running tasks in JS and was keen to find out about how to break them up and how they perform.

I decided to try a recursive function out, which calls itself from inside a setTimeout of 0ms. I figured that this would provide the breaks in the event loop for anything else that wanted to happen while it was running. But I also figured that while there is nothing else going on you will get maximum computation.

Here is what I came up with.

(I'm going to apologise for the code. I was experimenting in the console so this was quick and dirty.)

function test(i, ar, cal
Edit
Report