Topic: Asynchronous For-In Loops in Firefox (Page 1 of 1) Pages that link to <a href="" title="Pages that link to Topic: Asynchronous For-In Loops in Firefox (Page 1 of 1)" rel="nofollow" >Topic: Asynchronous For-In Loops in Firefox <span class="small">(Page 1 of 1)</span>\

Nervous Wreck (II) Inmate

From: United States
Insane since: Mar 2009

IP logged posted posted 04-29-2009 21:26 Edit Quote

This isn't cross-browser, but it is interesting nonetheless, and in any case, I haven't seen it posted anywhere else... Or mentioned anywhere else... Or listed in Google...

Anyway, it's possible to write an asynchronous for-in loop using a new feature of JavaScript 1.7: a FF2+ object called Iterator. Click here to read about how it works.

Anyway, here's a code for an object-based, Iterator-using, self-contained asynchronous looping mechanism.

AsyncLooper = 
         function(obj,iCallback,eCallback) {
         function(o,i,e,I) {
            var prop;
            for(var counter=0;counter<21;counter++) {
               try { // only way to check if there aren't any more properties
               } catch (e) { // if no more properties
                  return e(o)

// And a usage example:
myPointlessObject = {a:123,b:456,c:789,e:345,d:012};
STRING="myPointlessObject == "+myPointlessObject.toSource();
   function(o,n,v) {
      STRING+="\nmyPointlessObject['"+n+"'] == "+v
   function() {

To use it, you would call AsyncLooper.go() with the following arguments:
obj == The object to loop through.
iCallback == A function to be called on each iteration. It receives the object, property name, and property value as arguments.
eCallback == A function to be called when the loop ends. It receives the object as an argument.

And there you have it: an asynchronous for-in loop.

As a side note, it's possible to iterate through an Iterator using a for-in loop, but breaking out of the for-in loop kills the iterator (future for-in loops on it won't run, and any future calls to its next() method generate a StopException).

// Assume that myIterator is an Iterator.
for(i in myIterator) {
for(i in myIterator) {
   // even if the break statement
   // above ran before the Iterator
   // was "finished", this code will
   // never run...
// and calls to its next() method
// cause StopExceptions.


Nervous Wreck (II) Inmate

Insane since: May 2011

IP logged posted posted 05-31-2011 11:08 Edit Quote
Edit TP: spam removed

Post Reply
Your User Name:
Your Password:
Login Options: Remember Me On This Computer
Your Text:
Options: Show Signature
Enable Slimies
Enable Linkwords

« BackwardsOnwards »

Show Forum Drop Down Menu