Script speedup: Running functions asynchronously

This is something I’ve seen a long time ago, but never actually had the script for.  If you’ve got a slow process in your loop, for example:

for (var i=0;i<jedArray.length;i++) {
     reallySlowFunction("bob", "ted", fredObj, jedArray[i]);
}

You can just throw the function off to my function be executed in its own little time, and your loop can carry on.

for (var i=0;i<jedArray.length;i++) {
     setAsync(reallySlowFunction, ["bob", "ted", fredObj, jedArray[i]] );
}

Much faster!

The same thing can be reused for setTimeouts.  Everyone knows setTimeout is a bitch of a function, since it only takes a string.  That sucks.  So, instead of:

setTimeout("fredFunc("+ted+")", 1000);  // -> bleah!

You can use the setAsync function again:

setAsync(fredFunc, [ted], 1000);

Function defined as follows:

function setAsync(func, args, delay) {
   if (typeof(window.async)=="undefined") window.async = new Array();
   if (typeof(delay)=="undefined") delay=1;
   var myIndex = window.async.length;
   window.async[myIndex] = {"caller":setAsync.caller, "func":func, "args":args};
   var arglist = "";
   for (var i=0;i<args.length;i++) {
    arglist+="window.async["+myIndex+"].args["+i+"]"+",";
  }
   return setTimeout("window.async["+myIndex+"].func.call(window.async["+myIndex+"].caller,"+arglist.substring(0,arglist.length-1)+")", delay);
}

Any gurus (er, gurii?) out there, please let me know how this is currently solved in JS libraries – I’d be interested to know.

This entry was posted in Projects and tagged , . Bookmark the permalink.
  • http://kenneth.kufluk.com/ Kenneth

    Again, I’m out of date. Since IE5 and Firefox, you can pass functions directly to setTimeout.
    setTimeout(function() {}, delay);

    I’m not clear how you’d pass in any parameters to the function though, which is mostly what you’d want to do.

    Note, I’m using this approach for the stars above.

  • http://kenneth.kufluk.com Kenneth

    Again, I’m out of date. Since IE5 and Firefox, you can pass functions directly to setTimeout.
    setTimeout(function() {}, delay);

    I’m not clear how you’d pass in any parameters to the function though, which is mostly what you’d want to do.

    Note, I’m using this approach for the stars above.