javascript - Applying delay between each iteration of jQuery's .each() method -
having problems following block of code:
$('.merge').each(function(index) { var mergeel = $(this); settimeout(function() { self.mergeone(mergeel, self, index - (length - 1)); }, 500); });
i'm trying apply .500 second delay between each call of mergeone
, code applies .500 second delay before calling mergeone
on elements in array simultaneously.
if explain why code doesn't work , possibly working solution awesome, thanks!
here's general function can use iterate through jquery object's collection, delay between each iteration:
function delayedeach($els, timeout, callback, continuous) { var iterator; iterator = function (index) { var cur; if (index >= $els.length) { if (!continuous) { return; } index = 0; } cur = $els[index]; callback.call(cur, index, cur); settimeout(function () { iterator(++index); }, timeout); }; iterator(0); }
demo: http://jsfiddle.net/7ra9k/ (loop through once)
demo: http://jsfiddle.net/42txp/ (continuous looping)
the context , arguments passed callback should same how .each()
it.
if want make jquery plugin, can called $("selector").delayedeach(5000, func...
, use this:
$.fn.delayedeach = function (timeout, callback, continuous) { var $els, iterator; $els = this; iterator = function (index) { var cur; if (index >= $els.length) { if (!continuous) { return; } index = 0; } cur = $els[index]; callback.call(cur, index, cur); settimeout(function () { iterator(++index); }, timeout); }; iterator(0); };
demo: http://jsfiddle.net/vgh25/ (loop through once)
demo: http://jsfiddle.net/nydp7/ (continuous looping)
update
i added ability continuously loop through elements, parameter. passing true
continuously loop, while passing false
or nothing (or falsey) loop on elements once. code , fiddles include changes.
Comments
Post a Comment