Something like this (plain javascript, no jQuery needed;)):
var iterator = function(a, n) { var current = 0, l = a.length; return function() { end = current + n; var part = a.slice(current,end); current = end < l ? end : 0; return part; }; };
Then you can call it:
var next = iterator(arr, 3); next(); // gives the first three next(); // gives the next three. //etc.
Demo
In this form, the last iteration can return fewer elements. You can also expand it and force the function to take a variable step and another initial parameter.
If you want to wrap around, for example, if there are only two elements left to take elements from the very beginning, then it becomes a little more complicated;)
Update: The wrap will be something like this:
var iterator = function(a, n) { var current = 0, l = a.length; return function() { end = current + n; var part = a.slice(current,end); if(end > l) { end = end % l; part = part.concat(a.slice(0, end)); } current = end; return part; }; };
Demo
Felix kling
source share