I would like to perform a long running, node-by-node walk of the DOM, calling a function on each node, but without making the browser unresponsive.
So I’m thinking asynchronous is the way to go.
I think jQuery Deferred objects could provide a solution, but I haven’t managed to come up with one yet.
Can anyone give an example of how you could do this with jQuery (or another library, if one particularly stands out as suitable; or pure Javascript and DOM methods).
To further complicate things, I would like the ability to traverse in different orders, for example postorder, but not yet a requirement.
You could do this recursively with setTimeout. Since Javascript is single threaded you can create the illusion of having multiple threads by relinquishing the thread periodically. Calling setTimeout will queue the remaining work and process any outstanding events before continuing.
Here’s a working example with jQuery:
This will call
visitorwith all DOM nodes in depth-first pre-order traversal, then callvisitorwith an empty jQuery object to indicate that it’s done.visitormust call its second parameter to proceed with traversal: