Writing a Custom Iterator - J Query

You’ve selected multiple elements into a jQuery object, and you need to iterate through those
elements with a pause between each iteration, for example, to reveal elements one by one:

You tried using each(), but of course that revealed the elements all at once:


Write a custom iterator that uses setTimeout() to delay the callbacks over time:

Then simply change your .each() code to use .slowEach() and add the timeout value:


jQuery’s.each() method is not rocket science. In fact, if we strip the jQuery 1.3.2
implementation down to the code actually used in the most typical use (iterating over
ajQuery object), it’s a fairly straightforward loop:

That could also be coded in a more familiar way:

We can write similar functions to iterate over arrays or jQuery objects in other useful ways. A simpler example than .slowEach() is a method to iterate over a jQuery object in reverse:

This doesn’t attempt to handle all of the cases that .each() handles, just the ordinary case for typical jQuery code.
Interestingly enough, a custom iterator may not use a loop at all. .reverseEach() and the standard .each() both use fairly conventional loops, but there’s no explicit Java- Script loop in .slowEach(). Why is that, and how does it iterate through the elements without a loop?
JavaScript in a web browser does not have a sleep() function as found in many languages.There’s no way to pause script execution like this:

Instead, as with any asynchronous activity in JavaScript, the setTimeout() function takes a callback that is called when the time interval elapses. The .slowEach() method increments the “loop” variable i in the setTimeout() callback, using a closure to preserve the value of that variable between “iterations.” (See Recipe 5.2 for a discussion of closures.)
Like .each(), .slowEach() operates directly on the jQuery object or array you give it,so any changes you make to that array before it finishes iterating will affect the iteration. Unlike .each(), .slowEach() is asynchronous (the calls to the callback function happen after.slowEach() returns), so if you change the jQuery object or its elements after .slowEach() returns but before all the callbacks are done, that can also affect the iteration.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics